15

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.

Zoot
  • 2,217
  • 4
  • 29
  • 47
stdcall
  • 27,613
  • 18
  • 81
  • 125

1 Answers1

13

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 {
    ....
}
Usman Ismail
  • 17,999
  • 14
  • 83
  • 165
  • Great answer Usman. However, you probably want the @JsonTypeInfo on the parent instead of on the children. – Andrew McVeigh Nov 14 '12 at 02:44
  • We could do it that way too, in which case we would have to put name in the JsonSubTypes annotation something like the answer here: http://stackoverflow.com/questions/11798394/polymorphism-in-jackson-annotations-jsontypeinfo-usage – Usman Ismail Nov 14 '12 at 04:50
  • Jersey 2 uses Jackson 2.X.X which has both of these annotations so I don't see why it would not work. (See http://fasterxml.github.io/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonTypeName.html) – Usman Ismail Oct 08 '14 at 13:39
  • 2
    What if Parent is a third party interface and you cannot annotate it with JsonSubTypes ? Also adding the type to the Json (via JsonTypeInfo.Id.CLASS) is not a valid solution because the client should not be changed. – ampofila May 06 '16 at 07:41
  • That is not a good answer, because Jackson will add additional information in the json text, and the text added depends of JAVA, and your class. – ahll Jun 13 '16 at 07:38