Inheritance
Per-class annotation is a powerful method to include type information and can be very useful for complex use cases where a significant level of customization is necessary. However, this can only be achieved at the expense of complication. Per-class annotations override global default typing if type information is configured in both ways.
To make use of this method, the supertype should be annotated with @JsonTypeInfo and several other relevant annotations. This subsection will use a data model similar to the Vehicle structure in the previous example to illustrate per-class annotations. The only change is the addition of annotations on Vehicle abstract class, as shown below:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@Type(value = Car.class, name = "car"),
@Type(value = Truck.class, name = "truck")
})
public abstract class Vehicle {
// fields, constructors, getters and setters
}Convert JsonNode into POJO
In Jackson 2.4, you can convert as follows:
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);where jsonObjectMapper is a Jackson ObjectMapper.
In older versions of Jackson, it would be
MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);How to Modify JsonNode in Java
JsonNode is immutable and is intended for parse operation. However, it can be cast into ObjectNode (and ArrayNode) that allow mutations:
((ObjectNode)jsonNode).put("value", "NO");For an array, you can use:
((ObjectNode)jsonNode).putArray("arrayName").add(object.getValue());