概述:
XStream是一套简洁易用的开源类库,用于将java对象序列化成XML,或者将XML格式的数据反序列化为java对象,是java和XML之间的一个双向转换器。同时XStream也支持对JSON格式的转化,它的转化和XML的基本一样,只是在定义XStream时使用的驱动不同而已。
使用XStream操作XML:
定义一个User和LoginLog对象,使用这两个对象作为和XML进行转换的对象:
package cn.qing.xml.xstream;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
/**
* 用户信息
* @author ding
*
*/
//指定对象别名
@XStreamAlias("user")
public class User {
private int id;
private String name;
private String password;
private String phone;
//指定在生成时忽略集合对象
@XStreamImplicit
private List<LoginLog> logs;
public User(){}
public User(int id, String name, String password, String phone) {
super();
this.id = id;
this.name = name;
this.password = password;
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password
+ ", phone=" + phone + ", logs=" + logs + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<LoginLog> getLogs() {
return logs;
}
public void setLogs(List<LoginLog> logs) {
this.logs = logs;
}
}
LoginLog类:
package cn.qing.xml.xstream;
import java.util.Date;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
/**
* 用户登录日志
* @author ding
*
*/
@XStreamAlias("loginlog")
public class LoginLog {
//转换时将字段作为xml元素的属性
@XStreamAsAttribute
@XStreamAlias("logid")
private int logId;
@XStreamAsAttribute
private int userId;
private String logInfo;
private Date logTime;
public LoginLog(){}
public LoginLog(int logId, int userId, String logInfo, Date logTime) {
super();
this.logId = logId;
this.userId = userId;
this.logInfo = logInfo;
this.logTime = logTime;
}
@Override
public String toString() {
return "LoginLog [logId=" + logId + ", userId=" + userId + ", logInfo="
+ logInfo + ", logTime=" + logTime + "]";
}
public int getLogId() {
return logId;
}
public void setLogId(int logId) {
this.logId = logId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getLogInfo() {
return logInfo;
}
public void setLogInfo(String logInfo) {
this.logInfo = logInfo;
}
public Date getLogTime() {
return logTime;
}
public void setLogTime(Date logTime) {
this.logTime = logTime;
}
}
使用XStream操作XML的测试类代码:
package cn.qing.xml.xstream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XppDomDriver;
public class XStream4Xml {
private static XStream xStream;
static{
//在这里没有指定生成XML的驱动类,默认是使用XppDomDriver,也可以显示指定如:xStream = new XStream(new XppDomDriver());
xStream = new XStream();
//也可以指定使用DOM驱动
//xStream = new XStream(new DomDriver());
//指定xStream自动扫描添加了注解的对象
xStream.autodetectAnnotations(true);
}
/**
* @param args
*/
public static void main(String[] args) {
objdecToXml();
//xmlToObject();
//listToXml();
//xmlToListObject();
}
/**
* 将一个对象转换成xml
*/
public static void objdecToXml()
{
try {
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfo.xml";
User user = getUser();
OutputStream out = new FileOutputStream(new File(filePath));
StringWriter writer = new StringWriter();
//使用xStream将对象转换成xml并输出到文件中
//xStream.toXML(user, out);
//生成xml到StringWriter,就可以直接以String进行操作
xStream.toXML(user, writer);
System.out.println(writer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("对象生成XML失败....");
}
System.out.println("对象生成XML成功....");
}
/**
* 解析xml并转换成对象
*/
public static void xmlToObject()
{
try {
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfo.xml";
FileInputStream inputStream = new FileInputStream(new File(filePath));
//在生成时使用注解添加了别名,在解析时也必须添加在这里添加别名,否则会出错
xStream.alias("user", User.class);
User user = (User)xStream.fromXML(inputStream);
System.out.println(user);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 将包含多个对象的集合生成xml,类似与<beans><bean></bean><bean></bean><bean></bean></beans>的形式
*/
public static void listToXml()
{
try {
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfoList.xml";
OutputStream out = new FileOutputStream(new File(filePath));
ArrayList<User> list = new ArrayList<User>();
User user = getUser();
User user2 = getUser();
list.add(user);
list.add(user2);
//生成时使用users来替换集合list
xStream.alias("users", List.class);
xStream.toXML(list,out);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("对象生成XML失败....");
}
System.out.println("对象生成XML成功....");
}
/**
* 将带集合的xml解析为List对应的对象集合
*/
public static void xmlToListObject()
{
try {
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfoList.xml";
InputStream input = new FileInputStream(new File(filePath));
//在生成xml时把list改为别名users,所以在解析时也需要指定别名供转换使用
xStream.alias("users", List.class);
xStream.alias("user", User.class);
xStream.addImplicitCollection(User.class, "logs");
List<User> list = (List<User>)xStream.fromXML(input);
System.out.println("list.size():"+list.size());
for(User user : list)
{
System.out.println(user);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 封装User信息
* @return
*/
public static User getUser()
{
User user = new User(1,"ding","123456","13523537587");
List<LoginLog> logs = new ArrayList<LoginLog>();
LoginLog log = new LoginLog(1,1,"first login",new Date());
LoginLog log2 = new LoginLog(2,1,"second login",new Date());
logs.add(log);
logs.add(log2);
user.setLogs(logs);
return user;
}
}
生成的userInfo.xml
<user>
<id>1</id>
<name>ding</name>
<password>123456</password>
<phone>13523537587</phone>
<loginlog logid="1" userId="1">
<logInfo>first login</logInfo>
<logTime>2014-06-10 14:00:31.828 UTC</logTime>
</loginlog>
<loginlog logid="2" userId="1">
<logInfo>second login</logInfo>
<logTime>2014-06-10 14:00:31.828 UTC</logTime>
</loginlog>
</user>
生成的userInfoList.xml
<users>
<user>
<id>1</id>
<name>ding</name>
<password>123456</password>
<phone>13523537587</phone>
<loginlog logid="1" userId="1">
<logInfo>first login</logInfo>
<logTime>2014-06-10 12:59:25.177 UTC</logTime>
</loginlog>
<loginlog logid="2" userId="1">
<logInfo>second login</logInfo>
<logTime>2014-06-10 12:59:25.177 UTC</logTime>
</loginlog>
</user>
<user>
<id>1</id>
<name>ding</name>
<password>123456</password>
<phone>13523537587</phone>
<loginlog logid="1" userId="1">
<logInfo>first login</logInfo>
<logTime>2014-06-10 12:59:25.177 UTC</logTime>
</loginlog>
<loginlog logid="2" userId="1">
<logInfo>second login</logInfo>
<logTime>2014-06-10 12:59:25.177 UTC</logTime>
</loginlog>
</user>
</users>
使用XStream从XML中可以解析得到对应的对象,可以自行测试。
使用XStream操作JSON
还是使用User和LoginLog这两个对象
package cn.qing.xml.xstream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
public class XStream4JSON {
private static XStream xStream;
static{
//使用JsonHierarchicalStreamDriver驱动生成的JSON格式的数据,默认是有格式的
xStream = new XStream(new JsonHierarchicalStreamDriver());
//使用JettisonMappedXmlDriver驱动生成JSON格式的输出,默认是没有格式
//xStream = new XStream(new JettisonMappedXmlDriver());
//JsonHierarchicalStreamDriver和JettisonMappedXmlDriver都可以生成JSON数据,可以根据情况选择
//指定xStream自动扫描添加了注解的对象
xStream.autodetectAnnotations(true);
}
/**
* @param args
*/
public static void main(String[] args) {
//objectToJson();
//jsonToObject();
listToJson();
//jsonToListObject();
}
/**
* 将对象以JSON格式输出到文件
*/
public static void objectToJson()
{
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfo4json.txt";
User user = getUser();
try {
//生成JSON数据到指定文件
OutputStream out = new FileOutputStream(new File(filePath));
StringWriter writer = new StringWriter();
//生成JSON到StringWriter中,然后直接使用JSON数据
//xStream.toXML(user,writer);
xStream.toXML(user,out);
System.out.println(writer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("json 数据生成...");
}
/**
* 将JSON格式的数据转换成对象
*/
public static void jsonToObject()
{
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfo4json.txt";
try {
FileInputStream inputStream = new FileInputStream(new File(filePath));
xStream.alias("user", User.class);
User user = (User)xStream.fromXML(inputStream);
System.out.println(user);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 将List集合对象转换成JSON格式的数据
*/
public static void listToJson()
{
try {
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfoList4json.txt";
OutputStream out = new FileOutputStream(new File(filePath));
ArrayList<User> list = new ArrayList<User>();
User user = getUser();
User user2 = getUser();
list.add(user);
list.add(user2);
//生成时使用users来替换集合list
xStream.alias("users", List.class);
xStream.toXML(list,out);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("对象生成XML失败....");
}
System.out.println("对象生成XML成功....");
}
/**
* 将带集合的json解析为List对应的对象集合
*/
public static void jsonToListObject()
{
try {
String filePath = "F:\\myEclipseProject\\xmlDemo\\WebRoot\\xmlFolder\\userInfoList4json.txt";
InputStream input = new FileInputStream(new File(filePath));
//在生成xml时把list改为别名users,所以在解析时也需要指定别名供转换使用
xStream.alias("users", List.class);
xStream.alias("user", User.class);
xStream.addImplicitCollection(User.class, "logs");
List<User> list = (List<User>)xStream.fromXML(input);
System.out.println("list.size():"+list.size());
for(User user : list)
{
System.out.println(user);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 封装User信息
* @return
*/
public static User getUser()
{
User user = new User(1,"ding","123456","13523537587");
List<LoginLog> logs = new ArrayList<LoginLog>();
LoginLog log = new LoginLog(1,1,"first login",new Date());
LoginLog log2 = new LoginLog(2,1,"second login",new Date());
logs.add(log);
logs.add(log2);
user.setLogs(logs);
return user;
}
}
生成的userInfo4json.txt
{"user": {
"id": 1,
"name": "ding",
"password": "123456",
"phone": "13523537587",
"loginlog": {
"@logid": "1",
"@userId": "1",
"logInfo": "first login",
"logTime": "2014-06-10 13:41:07.251 UTC"
},
"loginlog": {
"@logid": "2",
"@userId": "1",
"logInfo": "second login",
"logTime": "2014-06-10 13:41:07.251 UTC"
}
}}
生成的userInfoList4json.txt
{"users": [
{
"id": 1,
"name": "ding",
"password": "123456",
"phone": "13523537587",
"loginlog": {
"@logid": "1",
"@userId": "1",
"logInfo": "first login",
"logTime": "2014-06-10 13:42:55.973 UTC"
},
"loginlog": {
"@logid": "2",
"@userId": "1",
"logInfo": "second login",
"logTime": "2014-06-10 13:42:55.973 UTC"
}
},
{
"id": 1,
"name": "ding",
"password": "123456",
"phone": "13523537587",
"loginlog": {
"@logid": "1",
"@userId": "1",
"logInfo": "first login",
"logTime": "2014-06-10 13:42:55.973 UTC"
},
"loginlog": {
"@logid": "2",
"@userId": "1",
"logInfo": "second login",
"logTime": "2014-06-10 13:42:55.973 UTC"
}
}
]}
通过上面的测试代码可以看出,使用XStream操作XML和JSON其实是一样的,只是在创建XStream时,指定的驱动不同。