In the last example we persisted polymorphic type information as JSON property by using @JsonTypeInfo with include=JsonTypeInfo.As.PROPERTY. Sometime it might not be possible to persist type info as JSON property (may be there's a conflict), in that case we can persist it as a wrapper. We have two options:
WRAPPER_OBJECT
This wraps typed JSON value in a JSON Object that has a single entry, where key is serialized as type's identifier, and value is the actual JSON object.
Example:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT)
public abstract class Shape {
}
above will serialized as:
{"shapes":[{"com.logicbig.example.Rectangle":{"w":3,"h":6}},{"com.logicbig.example.Circle":{"radius":5}}]}
WRAPPER_ARRAY
This wraps typed JSON value in a 2-element JSON array: first element is the type's identifier, and second element is the actual JSON object.
Example:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY)
public abstract class Shape {
}
{"shapes":[["com.logicbig.example.Rectangle",{"w":3,"h":6}],["com.logicbig.example.Circle",{"radius":5}]]}
Complete Example
Java Objects
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT)
public abstract class Shape {
}
public class Rectangle extends Shape {
private int w;
private int h;
.............
}
public class Circle extends Shape {
int radius;
.............
}
public class View {
private List<Shape> shapes;
.............
}
Serializing/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))));
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":[{"com.logicbig.example.Rectangle":{"w":3,"h":6}},{"com.logicbig.example.Circle":{"radius":5}}]} -- deserializing -- View{shapes=[Rectangle{w=3, h=6}, Circle{radius=5}]}
Example ProjectDependencies 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
|