廢話不說了,就是不想定義太多的java bean,有時候需求比較簡單,就想著直接用java的集合類來替換太多的java bean定義,看下面的代碼例子
[java]
- package org.garbagecan.xstreamstudy.converter;
-
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import com.thoughtworks.xstream.XStream;
- import com.thoughtworks.xstream.io.xml.DomDriver;
-
- public class TestMapListConverter {
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static void main(String[] args) {
- XStream xstream = new XStream(new DomDriver());
- Map map = new HashMap();
-
- List list1 = new ArrayList();
- list1.add(new T("a1", "b1", "c1"));
- list1.add(new T("a2", "b2", "c2"));
- List list2 = new ArrayList();
- list2.add(new T("a3", "b3", "c3"));
- list2.add(new T("a4", "b4", "c4"));
- map.put("t1", list1);
- map.put("t2", list2);
-
- xstream.alias("classes", Map.class);
- xstream.alias("class", Map.Entry.class);
- xstream.alias("name", String.class);
-
- xstream.alias("fields", List.class);
- xstream.alias("field", T.class);
- xstream.aliasAttribute(T.class, "a", "a");
- xstream.aliasAttribute(T.class, "b", "b");
- xstream.aliasAttribute(T.class, "c", "c");
-
- System.out.println(xstream.toXML(map));
-
- System.out.println((Map)xstream.fromXML(xstream.toXML(map)));
- }
- }
-
- class T {
- public T(String a, String b, String c) {
- this.a = a;
- this.b = b;
- this.c = c;
- }
- private String a;
- private String b;
- private String c;
- public String getA() {
- return a;
- }
- public void setA(String a) {
- this.a = a;
- }
- public String getB() {
- return b;
- }
- public void setB(String b) {
- this.b = b;
- }
- public String getC() {
- return c;
- }
- public void setC(String c) {
- this.c = c;
- }
- @Override
- public String toString() {
- return org.apache.commons.lang.builder.ToStringBuilder.reflectionToString(this);
- }
- }
運行上面的例子得到的xml內如如下:
[html]
- <classes>
- <class>
- <name>t2</name>
- <fields>
- <field a="a3" b="b3" c="c3"/>
- <field a="a4" b="b4" c="c4"/>
- </fields>
- </class>
- <class>
- <name>t1</name>
- <fields>
- <field a="a1" b="b1" c="c1"/>
- <field a="a2" b="b2" c="c2"/>
- </fields>
- </class>
- </classes>
得到的java對象內容如下:
[java]
- {t2=[org.garbagecan.xstreamstudy.converter.T@b166b5[a=a3,b=b3,c=c3], org.garbagecan.xstreamstudy.converter.T@1837697[a=a4,b=b4,c=c4]], t1=[org.garbagecan.xstreamstudy.converter.T@1decdec[a=a1,b=b1,c=c1], org.garbagecan.xstreamstudy.converter.T@a1807c[a=a2,b=b2,c=c2]]}