假设我有一个名为的抽象类AbstractItem
,用作另一个类中的字段。当我使用 XStream 生成 XML 时,我希望元素标记基于AbstractItem
.
我得到什么:
<Test>
<item class="Item1" name="name 1" description="description 1"/>
</Test>
我想要的是:
<Test>
<Item1 name="name 1" description="description 1"/>
</Test>
XStream
我尝试通过执行以下操作在实例上设置别名:
stream.alias("Item1", Item1.class);
并且还使用:
stream.aliasType("Item1", Item1.class);
以上任何一种都不起作用。
为了清楚起见,这里是上述的可运行示例:
测试.java
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Test")
public class Test {
public AbstractItem item;
public static void main(String[] args){
Test t1 = new Test();
Item1 item1 = new Item1();
item1.name = "name 1";
item1.description = "description 1";
t1.item = item1;
XStream stream = new XStream();
stream.setMode(XStream.NO_REFERENCES);
stream.autodetectAnnotations(true);
stream.alias("Item1", Item1.class);
System.out.println(stream.toXML(t1));
}
}
抽象项目.java
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
public abstract class AbstractItem {
@XStreamAsAttribute
public String name;
}
项目1.java
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
public class Item1 extends AbstractItem {
@XStreamAsAttribute
public String description;
}
更新: 我试图使用转换器类来做到这一点,但它仍然不正确:
stream.registerConverter(
new Converter(){
@Override
public boolean canConvert(Class type) {
if (AbstractItem.class.isAssignableFrom(type)){
return true;
}
return false;
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
AbstractItem item = (AbstractItem)source;
if(source instanceof Item1){
writer.startNode("Item1");
writer.addAttribute("description",((Item1)item).description);
} else if(source instanceof Item2){
writer.startNode("Item2");
writer.addAttribute("description", ((Item2)item).description);
} else {
writer.startNode("Item");
}
writer.addAttribute("name", item.name);
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
// TODO Auto-generated method stub
AbstractItem item = null;
String nodeName = reader.getNodeName();
if (nodeName.equals("Item1")){
item = new Item1();
((Item1)item).description = reader.getAttribute("description");
} else if (nodeName.equals("Item2")){
item = new Item2();
((Item2)item).description = reader.getAttribute("description");
}
item.name = reader.getAttribute("name");
return item;
}
});
我现在得到的结果是:
<Test>
<item class="Item1">
<Item1 description="description 1" name="name 1"/>
</item>
</Test>