简体   繁体   English

类包含泛型时的Jackson序列化错误

[英]Jackson serialization error when class has generics in it

So I have a class that I want jackson to serialize. 所以我有一个让杰克逊序列化的类。

public class MyClass<T extends MyInterface> {

   private T myGeneric;
   private String desc;

   ....
}

public interface MyInterface {
   String getSomeString();
}

public class MySubClass implements MyInterface {
  private String info;
  ....

  @Override
  public getSomeString() {
     return "";
  }
}

MyClass can have many types of other classes under it's myGeneric field. MyClassmyGeneric字段下可以具有许多其他类型的类。 The problem is that when I pass my JSON to the server, then Jackson throws an error: problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information . 问题是,当我将JSON传递到服务器时,杰克逊引发了一个错误: problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information

I investigated around and mostly only found examples of how to solve jackson problems with abstract classes but none for this kind of problem. 我到处研究,几乎只找到了如何用抽象类解决杰克逊问题的示例,但没有找到解决此类问题的示例。 I also tried using the @JsonTypeInfo and @JsonSubTypes annotations to list what kind of classes can go under MyClass but I am not sure if what I did was just wrong or not because it is hard to find any similar examples with them and the documentation in here: was not really helpful also. 我还尝试使用@JsonTypeInfo@JsonSubTypes批注列出MyClass下可以使用的类,但是我不确定我所做的是否是错误的,因为很难在它们和文档中找到任何类似的例子。 在这里:也没有真正的帮助。

Is this kind of problem solvable with Jackson annotations or I need to write a custom serializer for my class? 杰克逊(Jackson)注释是否可以解决此类问题,或者我需要为自己的课程编写自定义序列化程序?

I am testing the serialization like this: 我正在测试这样的序列化:

String json = "myJson";
ObjectMapper mapper = new ObjectMapper();
MyClass myClass = mapper.readValue(json, MyClass.class);

Jackson can't deserialize abstract types without additional info: when you have JSON with field 杰克逊无法在没有其他信息的情况下反序列化抽象类型:当您将JSON与字段一起使用时

"myGeneric" : { "field1" : 1, "field2" : 2}

you have no idea what is the class of the myGeneric object. 您不知道myGeneric对象的类是什么。

So you have two options: use @JsonTypeInfo annotation or to create custom deserializer. 因此,您有两个选择:使用@JsonTypeInfo批注或创建自定义反序列化器。 Example: 例:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
private T myGeneric ;

After that, serialized myGeneric field will look something like that: 之后,序列化的myGeneric字段将如下所示:

"myGeneric" : { "field1" : 1, "field2" : 2, "@class" : "com.project.MySubClass"}

Deserializer will use this info to instantiate an object of correct type 反序列化器将使用此信息来实例化正确类型的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM