简体   繁体   English

使用 Jackson 进行多态反序列化,而“类型”和“值”是分开的字段

[英]Polymorphic deserialization with Jackson while 'type' and 'value' are separated fields

an API returns the following JSON: API 返回以下 JSON:

"objectA":{
  "type":"typeA",
  "value":{
    "propertyA":{
      "propertyAA":"3000",
      "propertyAB":3
    },
    "propertyB":10
  }
}

While "type" can be a wide range of classes and the "value" field contains the properties of that object.虽然“类型”可以是广泛的类,而“值”字段包含该 object 的属性。 Is there an out of the box / annotation based solution provided by Jackson to solve this? Jackson 是否有开箱即用/基于注释的解决方案来解决这个问题?

Before the last update by the API provider, the API was returning:在 API 提供程序最后一次更新之前,API 正在返回:

"objectA":{"type":"typeA","propertyA":{"propertyAA":"3000","propertyAB":3},"propertyB":10} "objectA":{"type":"typeA","propertyA":{"propertyAA":"3000","propertyAB":3},"propertyB":10}

Which I was able to parse using:我能够使用以下方法解析:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @Type(value = TypeA.class, name = "typeA"),
[...]

As stated above, I am wondering if there is a Jackson configuration that allows to configure both, the field containing the type and the field which contains the actual object.如上所述,我想知道是否有允许配置两者的 Jackson 配置,包含类型的字段和包含实际 object 的字段。

Thank you very much and best regards!非常感谢和最好的问候!

I temporary solved this by introducing a wrapper object which handles the 'type' and 'value' fields.我通过引入处理“类型”和“值”字段的包装器 object 暂时解决了这个问题。 For the 'value' field I used the "EXTERNAL_PROPERTY" approach as shown here: Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected对于“值”字段,我使用了“EXTERNAL_PROPERTY”方法,如下所示: Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY 无法按预期工作

Works, but still does not feel very clean:( So if someone knows a better approach please share it: :)有效,但仍然感觉不是很干净:(所以如果有人知道更好的方法,请分享::)

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

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