Search code examples
javaxmlxstream

Mapping XML to POJO using xstream


I'm using XStream to map XML to the corresponding POJO. My XML structure is as below

<myTag>
<TagABC>
   <x> ... </x>
   <y> ... </y>
</TagABC>
    .
    .
    .
<TagABC>
   <x> ... </x>
   <y> ... </y>
</TagABC>
</myTag>

So there are multiple TagABC. I have defined TagABC in my POJO as

private List<TagABCHolder> TagABC;

where TagABCHolder is another POJO that simply contains x, y and their getter, setter

Now when I try to do the mapping using XStream with the code below

xstream.alias("TagABC", TagABCHolder.class);

xstream.fromXML(xml); 

This does not recognize the List structure defined in POJO for TagABC and throws the error below

 ---- Debugging information ----
 message             : x: x
 cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
 cause-message       : x: x
 class               : com.a.b.c.testing.common.TagABCHolder
 required-type       : java.util.ArrayList
 path                : /myTag/TagABC/x
 line number         : 1

Any idea how can I resolve this?


Solution

  • I got the solution.

    This is just a trick with the annotations.

    Here's what I did:

    I added @XStreamImplicit annotation in the POJO (TagABCHolder)

    @XStreamImplicit(itemFieldName="TagABC")
    private List<TagABCHolder> TagABC;
    

    and just processed the annotations placed within the POJO from the code where I was mapping

    xstream.processAnnotations(TagABCHolder.class);
    

    That's it!!!