JSON、Jersey 和 Jackson 中的多态性 [英] Polymorphism in JSON, Jersey and Jackson
问题描述
Jackson with Jersey 是否支持基于 JSON 的多态类?
Does Jackson with Jersey support polymorphic classes over JSON?
例如,假设我有一个 Parent 类和一个继承自它的 Child 类.而且,假设我想使用 JSON 发送 &通过 HTTP 接收父级和子级.
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) {
...
}
问题:如果我给这个函数(当然是通过 JSON)一个 Child 对象,它会起作用吗?Child 的额外成员字段也会被序列化吗?基本上,我想知道这些框架是否支持多态消费&回应.
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.
顺便说一句,我正在使用 Spring MVC.
BTW, I'm working with Spring MVC.
推荐答案
Jackson 确实支持多态,
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{
....
}
在父级中指定子类型:
@JsonSubTypes({ @JsonSubTypes.Type(value = Child.class), @JsonSubTypes.Type(value = SomeOther.class)})
public class Parent {
....
}
这篇关于JSON、Jersey 和 Jackson 中的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!