【发布时间】:2017-01-10 13:49:27
【问题描述】:
我想使用杰克逊注解反序列化 2 级多态子类型。 基本上我想使用 json annotations 和 jacksons 将以下 json 转换为 xml,如下所示
{
"mainSet": {
"name": "bla bla",
"myItems": [
{
"MySubItem": {
"id": 1,
"name": "Value1",
"itemAProperty1": "Some stuff",
"itemAProperty2": "Another property value",
"type": "MySubItemA"
}
},
{
"MySubItem": {
"id": 2,
"name": "Value2",
"itemBProperty1": 1000,
"itemBProperty2": "B property",
"type": "MySubItemB"
}
}
]
}
}
我想要的最终 XML 是
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mainTag schemaVersion="1" xmlns="http://www.utiba.com/xml/ns/brms/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>bla bla</name>
<MySubItem xsi:type="MySubItemA" id="1" name="value1" itemAProperty1="Some stuff" itemAProperty2="Another property value"/>
<MySubItem xsi:type="MySubItemB" id="2" name="value2" itemAProperty1=1000 itemAProperty2="B Property"/>
</mainTag>
我有以下一组类 - 主类
public abstract class MyItem {
private int id;
private String name;
//getter and setter
}
它有抽象子类
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MySubItem")
@XmlSeeAlso({
MySubItemA.class,
MySubItemB.class,
MySubItemC.class
})
public abstract class MySubItem extends MyItem {
private String itemAProperty1;
private String itemAProperty2;
//getter and setter
}
而 MySubItem 有具体的子类说 MySubItemA、MySubItemB、MySubItemC
现在最后,我们创建一个包含抽象类对象列表的客户端类
import java.util.ArrayList;
import java.util.List;
public class MainSet{
@XmlElements({
@XmlElement(name = "MysubItem", type = MySubItem.class),
})
private List<MyItem> myItems;
public List<MyItem> getMyItems() {
return this.myItems;
}
}
我尝试为 MyItem 创建 Mixin 类
@JsonTypeInfo(use=Id.MINIMAL_CLASS, include=As.PROPERTY, property="itemType")
@JsonSubTypes({
@Type(MySubItem.class)
})
And for 和 MySubItem
@JsonTypeInfo(use=Id.MINIMAL_CLASS, include=As.PROPERTY, property="type")
@JsonSubTypes({
@Type(MySubItemA.class)
@Type(MySubItemB.class)
@Type(MySubItemC.class)
})
我得到的错误是:
Error parsing JSON from client: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of MySubItem, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
at [Source: java.io.StringReader@26bd8952; line: 1, column: 498] (through reference chain: bla bla class ["mainSet"]->com.bla.bla["myItems"])
ISSUE : 为 myItems 列表创建 mixin 类,具有 2 级抽象子类层次结构
【问题讨论】:
标签: json serialization jackson polymorphism deserialization