Search code examples
javaxstream

XStream and Object class serialization


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?


Solution

  • 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);