[英]XStream and Object class serialization
I have beans which have Objects which can contain different types.我有 bean,它有可以包含不同类型的对象。 Now when I create XML it will add class attribute to serialized object. I would like to change that for example class simple name.
现在,当我创建 XML 时,它将向序列化的 object 添加 class 属性。我想更改它,例如 class 简单名称。
Example Java:示例 Java:
public class MyParentClass {
private Object childObjectAttribute; // Can be any instance of any interface ...
// Getters & setters etc..
XStream initialization: XStream 初始化:
public XStream getXStream()
{
XStream xstream = new XStream();
Class<?>[] c = { MyInterfaceImpl.class }; // MyInterfaceImpl has of course @XStreamAlias("MyInterface")
xstream.processAnnotations(c);
xstream.alias(MyInterface.class.getSimpleName(), MyInterface.class, MyInterfaceImpl.class);
return xstream;
}
Example XML:示例 XML:
<myParentClass>
<childObjectAttribute class="com.example.PossibleClass"/>
</myParentClass>
I would like to change com.example.PossibleClass to PossibleClass or something else.我想将 com.example.PossibleClass 更改为 PossibleClass 或其他。 Is that possible?
那可能吗?
Yes you can.是的你可以。 It's helps to reduce the size of generated document.
它有助于减少生成文档的大小。 It's a good practice to do so.
这样做是一种很好的做法。
Use XStream.alias() method.使用XStream.alias()方法。
This works for me.这对我有用。
PersonX person = new PersonX("Tito", "George");
XStream xstream = new XStream();
xstream.alias("MyPerson", PersonX.class);
String str = xstream.toXML(person);
System.out.println(str);
Without alias没有别名
<co.in.test.PersonX>
<firstName>Tito</firstName>
<lastName>George</lastName>
</co.in.test.PersonX>
With alias带别名
<MyPerson>
<firstName>Tito</firstName>
<lastName>George</lastName>
</MyPerson>
Is the below approach not working?以下方法不起作用吗?
workxstream.alias("PossibleClass", PossibleClass.class);
Yes, if you want the simple name of the class and you know the object's package you can:是的,如果您想要 class 的简单名称并且您知道对象的 package,您可以:
XStream xstream = new XStream();
xstream.aliasPackage("", "com.example");
Output xml: Output xml:
<myParentClass>
<childObjectAttribute class="PossibleClass"/>
</myParentClass>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.