Close

Jackson JSON - @JsonTypeInfo Annotation With JsonTypeInfo.Id.MINIMAL_CLASS Example

Following example shows how to use @JsonTypeInfo with option use = JsonTypeInfo.Id.MINIMAL_CLASS. Also check out @JsonTypeInfo tutorial.

use = JsonTypeInfo.Id.MINIMAL_CLASS option will serialize minimal relative package path. For example, for supertype "com.logicbig.example.Shape", and concrete type "com.logicbig.example.shapes.Circle", only ".shapes.Circle" would be included; for "com.logicbig.example.shapes.impl.Rectangle" only ".shapes.impl.Rectangle" would be included and for "com.logicbig.example.Square" only ".Square" will be included.

Java Objects

package com.logicbig.example;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "className")
public abstract class Shape {
}
package com.logicbig.example.shapes;

import com.logicbig.example.Shape;

public class Circle extends Shape {
  int radius;
    .............
}
package com.logicbig.example.shapes.impl;

import com.logicbig.example.Shape;

public class Rectangle extends Shape {
  private int w;
  private int h;
    .............
}
package com.logicbig.example;

public class Square extends Shape {
  private int side;
    .............
}
public class View {
  private List<Shape> shapes;
    .............
}

Serializing and deserializing

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      View v = new View();
      v.setShapes(new ArrayList<>(List.of(Rectangle.of(3, 6), Circle.of(5), Square.of(4))));

      System.out.println("-- serializing --");
      ObjectMapper om = new ObjectMapper();
      String s = om.writeValueAsString(v);
      System.out.println(s);

      System.out.println("-- deserializing --");
      View view = om.readValue(s, View.class);
      System.out.println(view);
  }
}
-- serializing --
{"shapes":[{"className":".shapes.impl.Rectangle","w":3,"h":6},{"className":".shapes.Circle","radius":5},{"className":".Square","side":4}]}
-- deserializing --
View{shapes=[Rectangle{w=3, h=6}, Circle{radius=5}, Square{side=4}]}

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.3.9

jackson-json-type-info-annotation-with-minimal-class Select All Download
  • jackson-json-type-info-annotation-with-minimal-class
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • shapes
                  • impl
                • Shape.java

    See Also