我有一个现有的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)
我在做什么错,我该如何解决?
答案 0 :(得分: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
有效载荷正常工作。