Close

Jackson JSON - Using @JsonTypeId to override polymorphic type information

[Last Updated: Aug 11, 2020]

@JsonTypeId annotation can be used to override polymorphic type information during serialization. It is typically used to override type information specified by @JsonTypeInfo.

Example

POJOs

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes(@JsonSubTypes.Type(value = Rectangle.class, name = "rectangle"))
public abstract class Shape {
}
@JsonTypeName("rectangle")
public class Rectangle extends Shape {
  @JsonTypeId
  private String typeId;
  private int w;
  private int h;
    .............
}

Main class

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Shape shape = Rectangle.of("RectShape", 3, 6);
      System.out.println(shape);
      System.out.println("-- serializing --");
      ObjectMapper om = new ObjectMapper();
      String s = om.writeValueAsString(shape);
      System.out.println(s);
  }
}
Rectangle{w=3, h=6}
-- serializing --
{"RectShape":{"w":3,"h":6}}

Without @JsonTypeId

If we remove @JsonTypeInfo from Rectangle#typeId then output will be:

Rectangle{typeId='RectShape', w=3, h=6}
-- serializing --
{"rectangle":{"typeId":"RectShape","w":3,"h":6}}

Example Project

Dependencies and Technologies Used:

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

@JsonTypeId Example Select All Download
  • jackson-json-type-id
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Rectangle.java

    See Also