使用现有同级属性值对属性进行 Jackson 多态反序列化

Jackson polymorphic deserialization of property using an existing sibling property value

提问人:Farrukh Najmi 提问时间:11/23/2019 最后编辑:Farrukh Najmi 更新时间:11/26/2019 访问量:1363

问:

我有一个我无法控制的现有/协议。RequestResponseJSON

示例 1:不需要任何多态反序列化的响应JSON

{
  "name" : "simple_response"
  "params" : {
    "success" : true
  }
}

示例 2:需要对 params 属性进行多态反序列化的响应JSON

{
  "name" : "settings_response",
  "params" : {
    "success" : true,
    "settings" : "Some settings info"
  }
}

我的类结构如下所示:

class Response { // Not abstract. Used if no specialized response properties needed
  @JsonProperty("params")
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
            property = "name")
    @JsonSubTypes({
            @JsonSubTypes.Type(value=GetSettingsResponseParams.class, name="settings_response")
    })
  Params params;
  String name; // Need to use its value to determine type of params
}

class Params {
  boolean success;
}

class GetSettingsResponseParams extends Params {
  String settings;
}

当我尝试反序列化“示例 2”中的 时,我得到:JSON

Unexpected token (END_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of com.foo.Params)

我做错了什么,我该如何解决?

java json jackson json 多态反序列化

评论


答:

2赞 Michał Ziober 11/23/2019 #1

Response模型应如下所示:

class Response {

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "name", visible = true)
    @JsonSubTypes({
            @JsonSubTypes.Type(value = GetSettingsResponseParams.class, name = "settings_response"),
            @JsonSubTypes.Type(value = Params.class, name = "simple_response")
    })
    private Params params;
    private String name;

    // getters, settets, toString, etc.
}

上述模型适用于两个呈现的有效载荷。JSON

评论

0赞 Farrukh Najmi 11/26/2019
Michal Zlober,对不起,我的示例 json 中有一个错误。name 属性是 param 属性的同级,这就是我在 JsonTypeInfo 上使用“include = JsonTypeInfo.As.EXTERNAL_PROPERTY”的原因。寻找限制我现有 api 的解决方案。对不起,这个错误。
0赞 Michał Ziober 11/26/2019
@FarrukhNajmi,在这种情况下是有道理的。我用你的类尝试了我的类版本,它们在给定的有效负载下按预期工作。您使用哪个版本?EXTERNAL_PROPERTYResponseJackson
1赞 Farrukh Najmi 12/2/2019
@MichalZlober,非常感谢您抽出宝贵时间通过一个非常清晰的例子帮助我解决这个问题。我的代码中有几个问题。JsonTypeInfo 中缺少 visible = true 是其中之一。另一个是在我的 Params 类中具有不同名称的属性上缺少 JsonProperty。