利用XStream將List轉為xml後指定String的別名
阿新 • • 發佈:2019-01-30
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)); } }
結果:
<tags>
<tag>foo</tag>
<tag>bar</tag>
</tags>
<notags>
<string>foo</string>
<string>bar</string>
</notags>