问题描述
这是我的班级层次结构:
Here is my class hierarchy:
Banana class:
Banana class:
@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 {
Abstract Vehicle class:
Abstract Vehicle class:
@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);
Banana对象具有@type属性。
Banana object has "@type" property.
Car对象具有type属性,如果我将car序列化为JSON则打印出来:
The Car object has "type" property and if I serialize car as JSON it prints out:
{"type":"car"}
但是,如果我将banana序列化为JSON,则会打印(只是类型: car缺失,其他对象属性可用):
However, if I serialize banana as JSON it prints(just "type":"car" is missing, other object properties are available):
{}
如果我执行banana.getMain()则打印出来
If I do banana.getMain() it prints out
{"type":"car"}
怎么可能?
我尝试了一个没有任何注释的简单对象(不是Car),它打印时工作正常
I tried a simple object(not Car) without any annotation and it works fine as it prints
{"type":"car"}
有人有任何想法吗?
推荐答案
所以答案是指定JacksonMapper的根类型为
So the answer is to specify root type for JacksonMapper as
jacksonMapper.writerWithType(new TypeReference< Banana< Car,String>>( ){})
这篇关于杰克逊 - 不能序列化泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!