Java Jackson多态反序列化(类依赖于JSON键) TL;博士
基本上,我的问题是我有一个包装器对象列表Java Jackson多态反序列化(类依赖于JSON键) TL;博士,java,json,jackson,deserialization,Java,Json,Jackson,Deserialization,基本上,我的问题是我有一个包装器对象列表 {"stuff": [ {"foobar" : {someObjectOfTypeA}}, {"barfoo" : {someObjectOfTypeB}}, {"foobar" : {someObjectOfTypeA}} ]} someObjectOfTypeX的类型取决于键“foobar”或“barfoo”的值。我如何将其反序列化?(目前)序列化不是问题 长版本 我对jackson了解不够,无法解决以下问题。我试过了,但我卡住了 我
{"stuff": [
{"foobar" : {someObjectOfTypeA}},
{"barfoo" : {someObjectOfTypeB}},
{"foobar" : {someObjectOfTypeA}}
]}
someObjectOfTypeX的类型取决于键“foobar”或“barfoo”的值。我如何将其反序列化?(目前)序列化不是问题
长版本 我对jackson了解不够,无法解决以下问题。我试过了,但我卡住了 我要解析的json结构如下所示:
{
"id": "foobar",
"responses": [
{
"responseType1": {
"code": 0,
"foo": "bar"
}
},
{
"responseType2": {
"code": 1,
"bar": {"foo": ...}
}
},
{
"responseType1": {
"code": 1,
"foo": "foobar"
}
}
]
}
我尝试使用jacksons完全数据绑定来反序列化它。我的POJO是:
// pseudocode
// the outermost object
@JsonCreator
ServiceResponse(
@JsonProperty("id") String id,
@JsonProperty("responses") ArrayList<ResponseWrapper> responses)
// every response has a wrapper. the wrapper is an object with just one key and one value. the value is an object of a certain class (ResponseTypeX extends AResponse), and the exact ResponseType is identified by the key (the key isn't the class name though).
@JsonCreator
ResponseWrapper(AResponse keyDependsOnTypeOfAResponse ???)
// base class for all responseTypeX classes
// all subclasses of AResponse have a code and a complex payload object
@JsonCreator
AResponse (
@JsonProperty("code") int code)
// one response type
// here, the payload is just a string, in reality it's a deep structure, so i dont want to parse this manually
@JsonCreator
ResponseType1 extends AResponse (
@JsonProperty("code") int code,
@JsonProperty("foo") String foo)
// one response type
@JsonCreator
ResponseType2 extends AResponse (
@JsonProperty("code") int code,
@JsonProperty("bar") SomeOtherObject foo)
但这失败了,可能是因为所有responsetype都是AResponse的子类,因此jackson会感到困惑。一些自定义反序列化处理是必要的。我建议在解决方案中包括一个foobar/barfoo的简单注册表(map)来输入条目,就像中的第六个示例一样。非常感谢!我已经读过你关于这个主题的一些文章,但我似乎忽略了这一篇。
@JsonCreator
ResponseWrapper(
@JsonProperty("responseKey1") ResponseType1 response1,
@JsonProperty("responseKey2") ResponseType2 response2,
@JsonProperty("responseKey3") ResponseType3 response3,
...)