XStream and Object class serialization
Asked Answered
D

2

5

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?

Dominiquedominium answered 9/4, 2012 at 11:14 Comment(1)
The only thing I can say about it is that PossibleClass without package name can cause deserialization problems when multiple packages contain a class of that name. For this, it may be impossible.Octavla
P
7

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);
Pt answered 9/4, 2012 at 12:1 Comment(4)
Updated question to contain XStream initialization.Dominiquedominium
Yes it works for String, Integer etc. and even Interfaces, but I have class Object, which seems to cause problems, because it can contain any class.Dominiquedominium
is 'workxstream.alias("PossibleClass", PossibleClass.class);' not working?Pt
Now it works, I don't really know what was problem, because now it seems to work with your examples. Thanx for help.Dominiquedominium
V
0

Yes, if you want the simple name of the class and you know the object's package you can:

XStream xstream = new XStream();
xstream.aliasPackage("", "com.example");

Output xml:

<myParentClass>
    <childObjectAttribute class="PossibleClass"/>
</myParentClass>
Vortex answered 3/3, 2016 at 14:6 Comment(1)
Please ignore this answer, I found this hack does not work because 1 package with blank alias causes deserialization problems with classes of another packages.Vortex

© 2022 - 2024 — McMap. All rights reserved.