Close

Jackson JSON - Serializing as supertype using 'as' attribute of @JsonSerialize

[Last Updated: Aug 11, 2020]

The attribute @JsonSerialize#as can be used to serialize the annotated declared type to the supertype.

Assuming A extends B:

 @Serialize(as = B.class)
 A a;

During serializing Jackson will skip the properties of class A and will only serialize the properties of class B.

Example

Java Objects

public class Rectangle {
  private int width;
  private int height;
    .............
}
public class RoundRectangle extends Rectangle {
  private int arcWidth;
    .............
}
package com.logicbig.example;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class View {
  @JsonSerialize(as = Rectangle.class)
  private RoundRectangle roundRectangle;
    .............
}

Main class

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      System.out.println("-- Java object to JSON (serialization) --");
      View view = new View();
      view.setRoundRectangle(RoundRectangle.of(5, 7, 2));
      System.out.println("Java object: " + view);

      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(view);//the arcWith property will be skipped
      System.out.println("JSON string: " + jsonString);

      System.out.println("-- JSON to Java object (deserialization) --");
      View view2 = om.readValue(jsonString, View.class);
      System.out.println("Java Object: " + view2);
  }
}
-- Java object to JSON (serialization) --
Java object: View{roundRectangle=RoundRectangle{arcWidth=2, width=5, height=7}}
JSON string: {"roundRectangle":{"width":5,"height":7}}
-- JSON to Java object (deserialization) --
Java Object: View{roundRectangle=RoundRectangle{arcWidth=0, width=5, height=7}}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.5: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.3.9

@JsonSerialize#as example. Select All Download
  • jackson-serialize-as
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • View.java

    See Also