【发布时间】:2017-01-06 12:45:59
【问题描述】:
这是我的类层次结构:
香蕉类:
@JsonTypeName("banana")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
public class Banana<T, M> extends Fruit<T, M> {
水果类:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({ @JsonSubTypes.Type(value = Banana.class, name = "banana")})
public class Fruit<T, M> {
private boolean ok;
private T main;
汽车类:
@JsonTypeName("car")
public class Car extends Vehicle {
抽象车辆类:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @JsonSubTypes.Type(value = Car.class), @JsonSubTypes.Type(value = AnyOtherClass.class) })
public abstract class Vehicle<K> {
private Date date;
private Id<?> id;
所以我创建了新对象:
Banana<Car, String> ba = new Banana<Car, String>();
Car car = new Car("test");
ba.setMain(car);
香蕉对象具有“@type”属性。
Car 对象具有“type”属性,如果我将 car 序列化为 JSON,它会打印出来:
{"type":"car"}
但是,如果我将香蕉序列化为它打印的 JSON(只是“类型”:“汽车”丢失,其他对象属性可用):
{}
如果我执行banana.getMain(),它会打印出来
{"type":"car"}
这怎么可能?
我尝试了一个没有任何注释的简单对象(不是汽车),它在打印时工作正常
{"type":"car"}
有人有什么想法吗?
【问题讨论】:
-
您能提供您的课程的完整源代码吗?不扩展Vehicle和Fruit还有问题可以试试吗?
-
它与 POJO 配合得很好。
标签: java json serialization jackson