【问题标题】:Jackson Polymorphic Deserialisation (where the class depends on the JSON key)Jackson 多态反序列化(类依赖于 JSON 键)
【发布时间】:2012-12-05 03:18:19
【问题描述】:

TL;DR

基本上,我的问题是我有一个包装对象列表

{"stuff": [
  {"foobar" : {someObjectOfTypeA}},
  {"barfoo" : {someObjectOfTypeB}},
  {"foobar" : {someObjectOfTypeA}}
]}

而 someObjectOfTypeX 的类型取决于键“foobar”或“barfoo”的值。我怎样才能反序列化这个? (目前)序列化不是问题。


长版

我没有足够的杰克逊来解决以下问题。我试过了,但是卡住了。

我要解析的 json 结构如下所示:

{
  "id": "foobar",
  "responses": [
    {
      "responseType1": {
        "code": 0,
        "foo": "bar"
      }
    },
    {
      "responseType2": {
        "code": 1,
        "bar": {"foo": ...}
      }
    },
    {
      "responseType1": {
        "code": 1,
        "foo": "foobar"
      }
    }
  ]
}

我尝试使用杰克逊完整数据绑定对其进行反序列化。我的pojo是:

// pseudocode

// the outermost object
@JsonCreator
ServiceResponse(
  @JsonProperty("id") String id, 
  @JsonProperty("responses") ArrayList<ResponseWrapper> responses)

// every response has a wrapper. the wrapper is an object with just one key and one value. the value is an object of a certain class (ResponseTypeX extends AResponse), and the exact ResponseType is identified by the key (the key isn't the class name though). 
@JsonCreator
ResponseWrapper(AResponse keyDependsOnTypeOfAResponse ???)

// base class for all responseTypeX classes
// all subclasses of AResponse have a code and a complex payload object
@JsonCreator
AResponse (
  @JsonProperty("code") int code)

// one response type
// here, the payload is just a string, in reality it's a deep structure, so i dont want to parse this manually
@JsonCreator
ResponseType1 extends AResponse (
  @JsonProperty("code") int code,
  @JsonProperty("foo") String foo)

// one response type
@JsonCreator
ResponseType2 extends AResponse (
  @JsonProperty("code") int code,
  @JsonProperty("bar") SomeOtherObject foo)

如您所见,responses 是一个包装对象数组;包装器对象的“有效负载”类由键标识(但键与类名不是 1:1 匹配)。我的 ResponseTypeX 是有限的,大约有 20 个,所以如果我必须手动进行 key:value 类型识别,我很高兴。

但是是否可以为 WrapperResponse 对象编写一个手动反序列化器并继续反序列化它的子对象并使用完整的数据绑定?如果有,怎么做?


我试图让 Wrapper 接受所有可能的 ResponseTypes 作为属性,希望它只会使“未设置”的那些无效,例如

@JsonCreator
ResponseWrapper(
  @JsonProperty("responseKey1") ResponseType1 response1,
  @JsonProperty("responseKey2") ResponseType2 response2,
  @JsonProperty("responseKey3") ResponseType3 response3,
  ...)

但这失败了,可能是因为所有 ResponseTypes 都是 AResponse 的子类,因此杰克逊会感到困惑。

【问题讨论】:

    标签: java json jackson deserialization


    【解决方案1】:

    一些自定义反序列化处理是必要的。我建议在解决方案中包含一个简单的 foobar/barfoo-to-type 条目的注册表(映射),就像my old blog post from May 25, 2011, "Deserialize JSON with Jackson into Polymorphic Types - A Complete Example" 中的第六个示例一样。

    【讨论】:

    • 非常感谢!我已经阅读了您有关该主题的一些文章,但似乎我忽略了这篇文章。
    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2017-04-04
    • 2023-03-18
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多