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开发者_StackOverflow社区 must contain List<String>
).
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));
In XStream version 1.4.5 you need to define different mapper objects for different class alias. The solution will be as following:
ClassAliasingMapper mapper = new ClassAliasingMapper(xstream.getMapper());
//tag
mapper.addClassAlias("tag", String.class);
xstream.registerLocalConverter(
Article.class,
"tags",
new CollectionConverter(mapper)
);
mapper = new ClassAliasingMapper(xstream.getMapper());
// this is required otherwise it will override the previos mapper
mapper.addClassAlias("category", String.class);
xstream.registerLocalConverter(
Article.class,
"categories",
new CollectionConverter(mapper)
);
Out of my mind:
@XStreamImplicit(itemFieldName="tag")
private List<String> categoryList;
Does it work?
精彩评论