maven 导入 jar
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("bean")
public class TestBean {
@XStreamAlias("姓名")
private String name;
@XStreamAlias("年龄")
private int age;
@XStreamImplicit(itemFieldName = "bean2")
private List
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List
return beans;
}
public void setBeans(List
this.beans = beans;
}
@Override
public String toString() {
// TODO 自动生成的方法存根
return ToStringBuilder.reflectionToString(this);
}
}
public class TestBean2 {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
// Bean转XML
// 初始化TestBean 对象
TestBean bean = new TestBean();
bean.setName("test");
bean.setAge(18);
List
TestBean2 bean1 = new TestBean2();
bean1.setName("test");
bean1.setAge(18);
TestBean2 bean2 = new TestBean2();
bean2.setName("test");
bean2.setAge(18);
list.add(bean1);
list.add(bean2);
// list 压入对象
bean.setBeans(list);
// 创建xstream对象
XStream xstream = new XStream();
// 自动侦查注解
xstream.autodetectAnnotations(true);
// 设置节点名称 绑定到指定的类 输出xml 的时候 就不会显示的 显示包了
//xstream.alias("TestBean", TestBean.class);
xstream.alias("TestBean2", TestBean2.class);
String xml = xstream.toXML(bean);
System.out.println(xml );
图片
//xml 转java bean
TestBean fromBean = (TestBean) xstream.fromXML(xml);
System.out.println(fromBean.getAge());
System.out.println(fromBean.getName());
System.out.println(fromBean.getBeans().get(0).getAge());
System.out.println(fromBean.getBeans().get(0).getName());
System.out.println(fromBean.getBeans().get(1).getAge());
System.out.println(fromBean.getBeans().get(1).getName());
图片
//list 结构的 TestBean2
List
TestBean2 b2= new TestBean2();
b2.setAge(1);
b2.setName("asdasd");
list2.add(b2);
TestBean2 b21= new TestBean2();
b21.setAge(2);
b21.setName("asdasd2");
list2.add(b21);
TestBean2 b22= new TestBean2();
b22.setAge(3);
b22.setName("asdasd3");
list2.add(b22);
xstream.alias("beans", java.util.List.class);
String list2xml = xstream.toXML(list2);
System.out.println(list2xml);
图片
//xml 转 list
List
for (TestBean2 testBean2 : fromLists) {
System.out.println(testBean2.getAge());
System.out.println(testBean2.getName());
}
图片
}