Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XStream and Object class serialization

Tags:

java

xstream

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?

like image 602
newbie Avatar asked Apr 09 '12 11:04

newbie


People also ask

What is XStream jar used for?

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.

Is XStream thread safe?

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.

What is XStream security framework?

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.

What is spring boot XStream?

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.


1 Answers

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);
like image 130
titogeo Avatar answered Sep 19 '22 12:09

titogeo