Search code examples
javaxmlxstream

Mapping Inheritance with XStream


When marshaling classes with inheritance only the child most class data is persisted.

For example, with the code:

public class Test {

    static class Person {
        String name;
    }

    static class Employee extends Person {
        String job;
    }

    public static void main(String[] args) {
        Employee me = new Employee();
        me.name = "Sam";
        me.job = "Developer";
        XStream xStream = new XStream();
        xStream.alias("employee", Employee.class);
        String xml = xStream.toXML(me);
        System.out.println(xml);
    }
}

My output looks like:

<employee>
  <job>Developer</job>
</employee>

How can I get XStream to output the parent class data?


Solution

  • You just have to switch to a newer XStream version. I ran your code with 1.2.2 and get this result:

    <employee>
      <job>Developer</job>
      <name>Sam</name>
    </employee>