简体   繁体   English

使用Jackson(Polymorphic)进行反序列化时缺少字段

[英]Missing field when deserializing using Jackson (Polymorphic)

I am trying to create an java SDK for a front-end library that takes JSON input. 我正在尝试为需要JSON输入的前端库创建一个java SDK。 Essentially, this SDK converts objects of certain type into JSON which is then consumed by that front-end library. 本质上,此SDK将特定类型的对象转换为JSON,然后由该前端库使用。

I am using jackson's polymorphic serialization/deserialization using its annotation system. 我使用其注释系统使用jackson的多态序列化/反序列化。

I have a base class A and 2 child classes B and C extending A. Class A has a type field, using which I decide what class (B or C) is to be used. 我有一个基类A和2个子类B和C扩展A.类A有一个类型字段,我决定使用哪个类(B或C)。 The syntax looks something like this: 语法如下所示:

@JsonTypeInfo({
  use = JsonTypeInfo.Id.NAME, 
  include = JsonTypeInfo.As.EXISTING_PROPERTY,
  property= "type"
})
@JsonSubTypes({
  @JsonSubTypes.Type(value = B.class, name = "b"),
  @JsonSubTypes.Type(value = C.class, name = "c")
})
public class A {
  private String type;

  public void setType(String type){
    this.type = type;
  }

  public String getType(){
    return this.type;
  }
}

public class B extends A {

}

public class C extends A {

}

So now, when I use Jackson's ObjectMapper 's readValue function and read the stringified JSON and convert to class A, I get the correct instance of either class A or class B based on the value of the type variable. 所以现在,当我使用Jackson的ObjectMapperreadValue函数并读取字符串化的JSON并转换为A类时,我会根据类型变量的值获得A类或B类的正确实例。 However , and here is the actual problem, when I try to use the function getType I always get null in those objects. 但是 ,这是实际问题,当我尝试使用函数getType我总是在这些对象中得到null I am not sure why jackson is not setting those values on the object. 我不确定为什么杰克逊没有在对象上设置这些值。

String json = "{ type: 'b' }"; // example input json

ObjectMapper om = new ObjectMapper();
A a = om.readValue(json, A.class);
// a is actually an instance of class B

a.getType()// this is null

You need to add to @JsonTypeInfo the parameter visible = true to avoid to remove the type when deserializing. 您需要将参数visible = true添加到@JsonTypeInfo ,以避免在反序列化时删除该类型。

@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME, 
  include = JsonTypeInfo.As.EXISTING_PROPERTY,
  property= "type",
  visible = true
)

public abstract boolean visible() default false public abstract boolean visible()默认为false

Property that defines whether type identifier value will be passed as part of JSON stream to deserializer (true), or handled and removed by TypeDeserializer (false). 定义类型标识符值是作为JSON流的一部分传递给反序列化程序(true),还是由TypeDeserializer(false)处理和删除的属性。 Property has no effect on serialization. 属性对序列化没有影响。 Default value is false, meaning that Jackson handles and removes the type identifier from JSON content that is passed to JsonDeserializer. 默认值为false,这意味着Jackson处理并从传递给JsonDeserializer的JSON内容中删除类型标识符。

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

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