如何重命名XStream列表元素?

时间:2011-07-29 18:51:43

标签: java xml-serialization xstream

我的模型看起来像:

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

XStream序列化为XML,如下所示:

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

我的问题是如何才能使<string>foo</string>成为<tag>foo<tag><string>bar</string>成为<category>bar</category>?我无法更改模型的结构,因为我使用Morphia ODM创建文章实例(文章必须包含List<String>)。

3 个答案:

答案 0 :(得分:5)

This post可能对您有用。

Nutshell版本:

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));

答案 1 :(得分:1)

在XStream版本1.4.5中,您需要为不同的类别名定义不同的映射器对象。解决方案如下:

    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)
    );

答案 2 :(得分:0)

出于我的想法:

@XStreamImplicit(itemFieldName="tag")
private List<String> categoryList;

有效吗?