用XStream写个demo给大家看看:
maven依赖:
com.thoughtworks.xstream
xstream
1.3.1
xpp3
xpp3
1.1.4c
三个类:
Student.javapackage com.simpco.xstreamtest;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Student")
public class Student {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + "]";
}
}
Root.javapackage com.simpco.xstreamtest;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Root")
public class Root {
@XStreamAlias("StudentList")
private List studentList;
public List getStudentList() {
return studentList;
}
public void setStudentList(List studentList) {
this.studentList = studentList;
}
public void addStudent(Student student){
if(studentList==null){
studentList = new ArrayList();
}
studentList.add(student);
}
}
运行 App.javapackage com.simpco.xstreamtest;
import com.thoughtworks.xstream.XStream;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ){
XStream xstream = new XStream();
Root root = new Root();
Student student = new Student();
student.setName("张三");
student.setSex("男");
root.addStudent(student);
Student student1 = new Student();
student1.setName("李四");
student1.setSex("女");
root.addStudent(student1);
// xstream.alias("root", Root.class);
// xstream.alias("Student", Student.class);
// Annotations.configureAliases(xstream, Student.class);
xstream.processAnnotations(Root.class);
xstream.processAnnotations(Student.class);//声明使用Student中的注解别名
String xml = xstream.toXML(root);
String top = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
System.out.println(top+xml);
// Root rootObj = (Root)xstream.fromXML(xml);
// System.out.println(JSON.toJSONString(rootObj));
}
}
预期结果:<?xml version="1.0" encoding="UTF-8"?>
张三
男
李四
女