Does Jackson with Jersey support polymorphic classes over JSON?
Let's say, for instance, that I've got a Parent class and a Child class that inherits from it. And, let's say I want to use JSON to send & receive both Parent and Child over HTTP.
public class Parent {
...
}
public class Child extends Parent {
...
}
I've thought about this kind of implementation:
@Consumes({ "application/json" }) // This method supposed to get a parent, enhance it and return it back
public @ResponseBody
Parent enhance(@RequestBody Parent parent) {
...
}
Question: If I give this function (through JSON of course) a Child object, will it work? Will the Child's extra member fields be serialized, as well ? Basically, I want to know if these frameworks support polymorphic consume & respond.
BTW, I'm working with Spring MVC.
Jackson can serialize and deserialize polymorphic data structures very easily. The CarTransporter can itself carry another CarTransporter as a vehicle: that's where the tree structure is! Now, you know how to configure Jackson to serialize and deserialize objects being represented by their interface.
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.
@JsonSubTypes – indicates sub-types of the annotated type. @JsonTypeName – defines a logical type name to use for annotated class.
Advertisements. @JsonTypeInfo is used to indicate details of type information which is to be included in serialization and de-serialization.
Jackson does support polymorphism,
In your child class annotate with a name:
@JsonTypeName("Child_Class")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
public class Child extends Parent{
....
}
In parent you specify sub types:
@JsonSubTypes({ @JsonSubTypes.Type(value = Child.class), @JsonSubTypes.Type(value = SomeOther.class)})
public class Parent {
....
}
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