xstream:实现JavaBean与XML/JSON的相互转换

时间:2020-11-27 19:05:12

     XML和JSON是两种很常用的数据描述和传输格式,在java里提供了完成JavaBean与这两种格式相互转换的组件,即XStream和JSON-lib,通过组件实现可以使得转换省事很多。这里主要讲解xstream的实现。首先要加载xstream包,当前版本是1.3.1,即xstream-1.3.1.jar。

这里先举个最简单的例子:

JavaBean:

package xstream;

public class Person {
private int id;
private String name;
private int age;
//这里省略setter和getter及构造方法
}

转换测试类:

package xstream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Convert
{
public static void main(String[] args)
{
Person person = new Person(1,"admin",20);
XStream xstream = new XStream(new DomDriver());
xstream.alias("Person", Person.class);
String xml = xstream.toXML(person);//JavaBean->XML
System.out.println(xml);

Person otherPerson = (Person) xstream.fromXML(xml);//XML->JavaBean
System.out.println("id:"+otherPerson.getId());
System.out.println("name:"+otherPerson.getName());
System.out.println("age:"+otherPerson.getAge());

XStream json = new XStream(new JsonHierarchicalStreamDriver());
json.alias("Person", Person.class);
String js = json.toXML(person);//JavaBean->JSON
System.out.println(js);
}
}

输出结果:

<Person>
<id>1</id>
<name>admin</name>
<age>20</age>
</Person>

id:1
name:admin
age:20

{"Person": {
  "id": 1,
  "name": "admin",
  "age": 20
}}