XStream可以把JavaBean对象转换成XML,同样也可以将XML转化成JavaBean对象,因为其简单使用深受广大程序员喜爱。
我发现很多人写文档不喜欢贴依赖,只吹牛不上代码不是耍流氓吗?
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
我们先来简单的应用一下,直接上代码:
class User {
private String name;
private int age;
private Subject subject;
getter...setter...
}
class Subject {
private String chinese;
private String mathematics;
getter...setter...
}
// 这里我们来测试一下
public static void main(String[] args) {
User user = new User();
user.setName("zhangsan");
user.setAge(18);
Subject subject = new Subject();
subject.setChinese("98分");
subject.setMathematics("100分");
user.setSubject(subject);
XStream xstream = new XStream(new DomDriver( "utf-8"));
xstream.allowTypesByRegExp(new String[] { ".*" });
xstream.ignoreUnknownElements();
xstream.processAnnotations(User.class);
String res = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
//javabean to xml
String xml = res + xstream.toXML(user);
System.out.println(xml);
}
然后我们来看看打印结果:
大家仔细看看标签里的属性,是不是不太符合XML报文的,这时我们需要给他取个别名,最简单的方式就是给个注解@XStreamAlias
@XStreamAlias("user")
class User {
private String name;
private int age;
private Subject subject;
getter...setter...
}
@XStreamAlias("subject")
class Subject {
private String chinese;
private String mathematics;
getter...setter...
}
再来看看运行结果:
看到这是不是觉得很熟悉,是不是拆箱即用很方便。