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

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

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

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

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

{
  "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)

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

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

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有效载荷正常工作。

本文链接:https://www.f2er.com/3048798.html

大家都在问