I am using Jackson to convert a big Json string into various classes and subclasses.
I have a list of objects, each containing a node object, a last result object and a children array. The children array contains a list of objects with exactly the same setup. This goes on for 3 or 4 layers.
Each layers' node is of a different subclass, which all extend from a node superclass. I have annotated the superclass node with following annotations:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Type1ResponseDto.class, name = "Type1"),
@JsonSubTypes.Type(value = Type2ResponseDto.class, name = "Type2"),
@JsonSubTypes.Type(value = Type3ResponseDto.class, name = "Type3"),
@JsonSubTypes.Type(value = Type4ResponseDto.class, name = "Type4"),
@JsonSubTypes.Type(value = Type5ResponseDto.class, name = "Type5")
})
This seems to work, since all subclasses get mapped.
However, this somehow results in the "type" property being set to null.
Any ideas as to why this happens?
Text. Json doesn't support the serialization of polymorphic type hierarchies. For example, if a property's type is an interface or an abstract class, only the properties defined on the interface or abstract class are serialized, even if the runtime type has additional properties.
A polymorphic deserialization allows a JSON payload to be deserialized into one of the known gadget classes that are documented in SubTypeValidator. java in jackson-databind in GitHub. The deserialized object is assigned to a generic base class in your object model, such as java. lang. Object or java.
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.
I needed to add visible=true
for the type property to show up:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type",visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = Type1ResponseDto.class,name = "Type1"),
@JsonSubTypes.Type(value = Type2ResponseDto.class, name = "Type2"),
@JsonSubTypes.Type(value = Type3ResponseDto.class, name = "Type3"),
@JsonSubTypes.Type(value = Type4ResponseDto.class, name = "Type4")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With