XStream: how to marshal/unmarshal lists in a custom converter?

tamm0r picture tamm0r · Sep 27, 2010 · Viewed 9.8k times · Source

I have the following class (legacy; not annotatable) that is serialized with a custom converter:

class Test {

    // some other variables

    List<SomeType> someTypeList;

}

A properly working converter for SomeType is already available. However I want the list to be serialized as if it was annotated with @XStreamAlias("someTypes").

In the end I expect the following format for someTypeList:

<someTypes class="list-type">
    <someType>
        ....
    </someType>
    ...
</someTypes>

How do I have to implement the marshal/unmarshal method to get the desired output? Calling context.convertAnother(someTypeList) didn't yield the expected result as the surrounding <someTypes> tag was missing.

Answer

jazzcool picture jazzcool · Jan 18, 2011

You wise to get the structure:

<someTypes class="list-type">  
<someType>  
....  
</someType>  
...  
</someTypes>

Look at the following code. For your list you need to tag:

@XStreamImplicit(itemFieldName="someType")  
List<someType>List;

Now, depending on what you got inside, you might need to create a custom converter. To refer to that you change a bit like this:

@XStreamImplicit(itemFieldName="someType")  @XStreamConverter(YourOwnConverter.class)  
List<SomeType> someTypeList;

Then create a converter class (YourOwnConverter) that would know how to un/marshal:

public boolean canConvert(Class type) 
{
    return type.equals(SomeType.class);
}

public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) 
{
    SomeType mytype = (SomeType) source;
    writer.addAttribute("position", mytype.getPosition());
    writer.setValue(mytype.getId());
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) 
{
    SomeType mytype = new SomeType();
    String position =  reader.getAttribute("position");
    ......  
        return mytype ;
}

Use this as example: http://x-stream.github.io/converter-tutorial.html