我有一个我无法控制的使用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)
我在做什么错,我该如何解决?
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.
}