杰克逊多态反序列化(其中类取决于JSON键)

3

简介

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

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

某些SomeObjectOfTypeX的类型取决于键“foobar”或“barfoo”的值。如何反序列化此内容?(目前)序列化不是问题。


详细说明

我不了解足够的Jackson以解决以下问题。我尝试过,但卡住了。

我想要解析的JSON结构如下:

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

我尝试使用Jackson的完全数据绑定进行反序列化。我的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是一个包装对象的数组;包装对象的“payload”类由键标识(但键与类名不是1:1匹配)。我的ResponseTypeX有限,大约有20个,因此如果我必须手动进行键值类型识别,我很高兴。
但是,是否可能编写手动反序列化程序来继续使用完全数据绑定对其子项进行反序列化?如果可以,该如何实现?
我尝试使Wrapper接受所有可能的ResponseTypes作为属性,希望它只会将“未设置”的属性置为空,例如:
@JsonCreator
ResponseWrapper(
  @JsonProperty("responseKey1") ResponseType1 response1,
  @JsonProperty("responseKey2") ResponseType2 response2,
  @JsonProperty("responseKey3") ResponseType3 response3,
  ...)

但是这个方法失败了,可能是因为所有的 ResponseTypes 都是 AResponse 的子类,因此 jackson 会混淆。
1个回答

3

非常感谢!我已经阅读了一些关于这个主题的文章,但似乎错过了这篇。 - stefs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接