出于兴趣,我尝试了这样做,而没有编写我自己的转换器。基本上我只是为某个类中的某个字段注册一个特殊的CollectionConverter指令版本。
相关片段:
ClassAliasingMapper mapper = new ClassAliasingMapper(xstream.getMapper());
mapper.addClassAlias("tag", String.class);
xstream.registerLocalConverter(
Test.class,
"tags",
new CollectionConverter(mapper)
);成熟的例子:
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.converters.collections.*;
import com.thoughtworks.xstream.mapper.*;
import java.util.*;
public class Test {
public List tags = new ArrayList();
public List notags = new ArrayList();
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));
}
}
没有测试,但这应该工作。没有?
xstream.alias("tag", java.lang.String.class);