Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
458 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 {
    ....
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...