Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

polymorphic deserialization of JSON with jackson, property type becomes "null"

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?

like image 292
Wim Berchmans Avatar asked Mar 11 '15 10:03

Wim Berchmans


People also ask

Is polymorphic Deserialization possible in system text JSON?

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.

What is polymorphic Deserialization?

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.

Does Jackson use Java serialization?

Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.

What is Jackson object serialization?

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.


1 Answers

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")
})
like image 164
Wim Berchmans Avatar answered Nov 03 '22 04:11

Wim Berchmans