Search code examples
javaxmldeserializationxstream

Convert XML to Object xstream ( Android )


I'm looking for help with the conversion of an xml to object via XStream , here is my XML

<main>
      <listDTO>
          <MyObject>
              <test>value1</test>
          </MyObject>
          <MyObject>
              <test>value2</test>
          </MyObject>

      </listDTO>
</main>

here are my classes.

public class First{
      MyObject[] listDTO;
}

public class MyObject{
      String test;
}

With xstream :

...
XStream xStream = new XStream();
xStream.alias("main",First.class);
xStream.alias("listDTO", MyObject.class);
xStream.addImplicitCollection(First.class,"listDTO");

....

The tag <listDTO> is a problem, and I can not change the XML . The classes were generated from wsdl with Eclipse .

Can you help me ?


Solution

  • Your code should look like this:

    XStream xStream = new XStream();
    xStream.alias("main", First.class);
    xStream.alias("MyObject", MyObject.class);
    

    First, you don't have implicit collection, but explicit one marked by listDTO tag. With implicit collection your XML would be:

    <main>
        <MyObject>
            <test>value1</test>
        </MyObject>
        <MyObject>
            <test>value2</test>
        </MyObject>
    </main>
    

    And second error you have made was adding listDTO alias for MyObject class. That should be replaced with MyObject alias, since you do have MyObject tag defined in your XML that corresponds to MyObject class.