Search code examples
javaxml-serializationxstream

How do I rename XStream list elements?


I have a model that looks like:

@XStreamAlias("article")
class Article {
  List<String> tags;
  List<String> categories;
}

XStream serializes to XML that looks like:

<article>
  <tags>
    <string>foo</string>
  </tags>
  <categories>
    <string>bar</string>
  </categories>
</article>

My question is how can I make it so that <string>foo</string> becomes <tag>foo<tag> and <string>bar</string> becomes <category>bar</category>? I'm unable to change the structure of my model since I am using the Morphia ODM to create the Article instances (article must contain List<String>).


Solution

  • This post may be of use to you.

    Nutshell version:

    ClassAliasingMapper mapper = new ClassAliasingMapper(stream.getMapper());
    mapper.addClassAlias("tag", String.class);
    mapper.addClassAlias("category", String.class);
    stream.registerLocalConverter(Article.class, "tags", new CollectionConverter(mapper));
    stream.registerLocalConverter(Article.class, "categories", new CollectionConverter(mapper));