Muhammad Imran Tariq Muhammad Imran Tariq - 3 months ago 21
Java Question

Xstream class within class

In Xstream can we use this:

class Cat {
int age;
String name;
Cat anotherSmallCat;
}


XML is

<cat><age>2</age><name>tom</name><cat><name>tommy</name></cat></cat>


I tried but getting exception.

com.thoughtworks.xstream.converters.ConversionException

Answer

Annotate your Cat as as below using @XStreamAlias,

@XStreamAlias("Cat")
public class Cat {

    int age;
    String name;

    @XStreamAlias("Cat")
    Cat anotherSmallCat;

}

Try to deserialize as below,

XStream xstream = new XStream();
xstream.processAnnotations(Cat.class);
Cat cat = (Cat) xstream.fromXML(new File("test.xml"));

Don't forget to use processAnnotations method.