我有一个现有的Request
/Response
协议,使用JSON
,但我无法控制。
示例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)
我做错了什么,该怎么修复它?
EXTERNAL_PROPERTY
是有意义的。我使用我的版本的Response
类与您的类,并且它们对于给定的有效载荷按预期工作。您使用哪个版本的Jackson
? - Michał Ziober