customising serialisation of java collections using xstream

Will Goring picture Will Goring · Nov 24, 2009 · Viewed 10.5k times · Source

I have an object that needs to be serialised as XML, which contains the following field:

List<String> tags = new List<String>();

XStream serialises it just fine (after some aliases) like this:

<tags>
  <string>tagOne</string>
  <string>tagTwo</string>
  <string>tagThree</string>
  <string>tagFour</string>
</tags>

That's OK as far as it goes, but I'd like to be able to rename the <string> elements to, say, <tag>. I can't see an obvious way to do that from the alias documentation on the XStream site. Am I missing something obvious?

Answer

jitter picture jitter · Nov 24, 2009

Out of interest I gave it a try to do it without writing my own converter. Basically I just register a special instructed version of CollectionConverter for a certain field in a certain class.

Relevant snippet:

ClassAliasingMapper mapper = new ClassAliasingMapper(xstream.getMapper());
mapper.addClassAlias("tag", String.class);
xstream.registerLocalConverter(
    Test.class,
    "tags",
    new CollectionConverter(mapper)
);

Full-blown example:

import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.converters.collections.*;
import com.thoughtworks.xstream.mapper.*;
import java.util.*;

public class Test {
    public List<String> tags = new ArrayList<String>();
    public List<String> notags = new ArrayList<String>();
    public Test(String tag, String tag2) {
        tags.add(tag); tags.add(tag2);
        notags.add(tag); notags.add(tag2);
    }
    public static void main(String[] args) {
        Test test = new Test("foo", "bar");
        XStream xstream = new XStream();

        ClassAliasingMapper mapper = new ClassAliasingMapper(xstream.getMapper());
        mapper.addClassAlias("tag", String.class);
        xstream.registerLocalConverter(
            Test.class,
            "tags",
            new CollectionConverter(mapper)
        );

        System.out.println(xstream.toXML(test));
    }
}

Not tested but this should work. No?

xstream.alias("tag", java.lang.String.class);