Reputation: 28880
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.
Upvotes: 15
Views: 8877
Reputation: 18669
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 {
....
}
Upvotes: 13