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

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...