Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism in JSON, Jersey and Jackson

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.

like image 633
stdcall Avatar asked Dec 19 '11 17:12

stdcall


People also ask

Can Jackson serialize interface?

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.

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.

What is @JsonSubTypes?

@JsonSubTypes – indicates sub-types of the annotated type. @JsonTypeName – defines a logical type name to use for annotated class.

What is @JsonTypeInfo?

Advertisements. @JsonTypeInfo is used to indicate details of type information which is to be included in serialization and de-serialization.


1 Answers

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 {
    ....
}
like image 105
Usman Ismail Avatar answered Nov 10 '22 16:11

Usman Ismail