I have beans which have Objects which can contain different types. Now when I create XML it will add class attribute to serialized object. I would like to change that for example class simple name.
Example Java:
public class MyParentClass {
private Object childObjectAttribute; // Can be any instance of any interface ...
// Getters & setters etc..
XStream initialization:
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:
<myParentClass>
<childObjectAttribute class="com.example.PossibleClass"/>
</myParentClass>
I would like to change com.example.PossibleClass to PossibleClass or something else. Is that possible?
XStream's primary purpose is for serialization. It allows existing Java objects to be converted to clean XML and then restored again, without modifications. This is particularly useful as a form of persistence (no complicated database mappings required) or for sending objects over the wire.
But in official document:XStream is not thread-safe while it is configured. Unfortunately, an annotation is defining a change in configuration that is now applied while object marshalling is processed.
The security framework supports the setup of a blacklist or whitelist scenario. Any application should use this feature to limit the danger of arbitrary command execution if it deserializes data from an external source.
XStream is a simple library to serialize objects to XML and back again. It does not require any mapping, and generates clean XML. For more information on XStream, refer to the XStream web site. The Spring integration classes reside in the org. springframework.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With