Jackson - cannot serialize generics

十年热恋 提交于 2019-12-24 12:29:16

问题


Here is my class hierarchy:

Banana class:

@JsonTypeName("banana")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
public class Banana<T, M> extends Fruit<T, M> {

Fruit class:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
    @JsonSubTypes({ @JsonSubTypes.Type(value = Banana.class, name = "banana")})
    public class Fruit<T, M> {
      private boolean ok;
      private T main;

Car class:

@JsonTypeName("car")
public class Car extends Vehicle {

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;

So I create new object:

Banana<Car, String> ba = new Banana<Car, String>();
Car car = new Car("test");
ba.setMain(car);

Banana object has "@type" property.

The Car object has "type" property and if I serialize car as JSON it prints out:

{"type":"car"}

However, if I serialize banana as JSON it prints(just "type":"car" is missing, other object properties are available):

{}

If I do banana.getMain() it prints out

{"type":"car"}

How it is possible?

I tried a simple object(not Car) without any annotation and it works fine as it prints

{"type":"car"}

Have someone any ideas thats going on?


回答1:


So the answer is to specify root type for JacksonMapper as

jacksonMapper.writerWithType(new TypeReference<Banana<Car, String>>() {})




回答2:


You will need to provide a more complete example of usage here. I suspect this is due to type parameterization (that is, trying to serialize instance of generic type) and Java Type Erasure, but it is impossible to say for sure without seeing code you are using.



来源:https://stackoverflow.com/questions/41506074/jackson-cannot-serialize-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!