Jackson多态反序列化(类依赖于JSON键)

时间:2012-12-05 03:18:20

标签: java json jackson deserialization

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"
      }
    }
  ]
}

我尝试使用jacksons完整数据绑定对其进行反序列化。我的pojos是:

// 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个,所以如果我必须做一个手动键:值类型识别,我很高兴。

但是是否可以为WrapperResponse对象编写手动反序列化器并继续使用完整数据绑定反序列化其子项?如果是这样,怎么样?


我试图让Wrapper接受所有可能的ResponseTypes作为属性,希望它只是取消“未设置”的那些,例如。

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

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

1 个答案:

答案 0 :(得分:3)

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