使用现有的同级属性值对属性进行杰克逊多态反序列化

问题描述 投票:0回答:1

我有一个我无法控制的使用Request的现有Response / JSON协议。

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

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

示例2:需要参数多态反序列化的响应JSON

{
  "params" : {
    "success" : true,
    "name" : "settings_response",
    "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-deserialization polymorphic-deserialization
1个回答
0
投票

name属性是params JSON Object的一部分。在POJO模型中,它应该是Params类的一部分:

class Params {
    private String name;
    private boolean success;

    // getters, settets, toString, etc.
}

此外,您还需要改进一点类型信息:

class Response {

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

    // getters, settets, toString, etc.
}
© www.soinside.com 2019 - 2024. All rights reserved.