com.thoughtworks.xstream
xstream
1.4.7
实体类见博客《Json字符串和Java对象转换利器——Jackson》。所有的实体类除了包名不同,成员都一样。
工具类XStreamUtil:
package org.xstream;
import java.io.Writer;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
public class XStreamUtil {
/**
* Java对象转Xml字符串(序列化)
* @param object
* @return
*/
public String bean2Xml(Object object){
XStream stream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
public void startNode(String name) {
// 去掉包名
if (name.indexOf(".") > -1) {
name = name.substring(name.lastIndexOf(".") + 1);
}
super.startNode(name);
};
};
}
});
return stream.toXML(object);
}
/**
* Xml字符串转Java对象(反序列化)
* @param xml
* @param rootName 根元素名称
* @param rootType 根元素对应的Java类型
* @param collectionTypes 集合类型
* @return
*/
public Object xml2Bean(String xml, String rootName, Class> rootType,
List> collectionTypes){
XStream stream = new XStream();
stream.alias(rootName, rootType);
for (Class> clazz : collectionTypes) {
stream.alias(clazz.getSimpleName(), clazz);
}
Object bean = stream.fromXML(xml);
return bean;
}
}
测试类XStreamUtilTest:
package org.xstream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.xstream.po.GetOrdersResponse;
import org.xstream.po.Order;
import org.xstream.po.PaginationResult;
import org.xstream.po.order.CheckoutStatus;
public class XStreamUtilTest {
XStreamUtil streamUtil;
GetOrdersResponse ordersResponse;
static String xmlStr;
@Before
public void before() {
streamUtil = new XStreamUtil();
ordersResponse = new GetOrdersResponse();
ordersResponse.setTimestamp("2007-12-10T16:12:55.184Z");
ordersResponse.setAck("Success");
ordersResponse.setBuild("e539_core_Bundled_5642307_R1");
ordersResponse.setVersion("539");
List orders = new ArrayList();
for (int i = 0; i < 3; i++) {
Order order = new Order();
order.setOrderID("OrderId_" + i);
order.setBuyerUserID("BuyerUserId_" + i);
CheckoutStatus checkoutStatus = new CheckoutStatus();
checkoutStatus.setEBayPaymentStatus("EBayPaymentStatus_" + i);
checkoutStatus.setLastModifiedTime("LastModifiedTime_" + i);
checkoutStatus.setStatus("Status_" + i);
order.setCheckoutStatus(checkoutStatus);
orders.add(order);
}
ordersResponse.setOrderArray(orders);
PaginationResult paginationResult = new PaginationResult();
paginationResult.setTotalNumberOfEntries("10");
paginationResult.setTotalNumberOfPages("5");
ordersResponse.setPaginationResult(paginationResult);
}
@Test
public void bean2Xml(){
xmlStr = streamUtil.bean2Xml(ordersResponse);
System.out.println("--------序列化---------");
System.out.println(xmlStr);
}
@Test
public void xml2Bean(){
System.out.println("----------反序列化---------");
System.out.println(streamUtil.xml2Bean(xmlStr,
GetOrdersResponse.class.getSimpleName(), GetOrdersResponse.class,
Arrays.asList(new Class>[]{Order.class})));
}
}
结果:
--------序列化---------
2007-12-10T16:12:55.184Z
Success
539
e539_core_Bundled_5642307_R1
10
5
OrderId_0
EBayPaymentStatus_0
LastModifiedTime_0
Status_0
BuyerUserId_0
OrderId_1
EBayPaymentStatus_1
LastModifiedTime_1
Status_1
BuyerUserId_1
OrderId_2
EBayPaymentStatus_2
LastModifiedTime_2
Status_2
BuyerUserId_2
----------反序列化---------
GetOrdersResponse [ack=Success, build=e539_core_Bundled_5642307_R1, orderArray=[Order [buyerUserID=BuyerUserId_0, checkoutStatus=CheckoutStatus [eBayPaymentStatus=EBayPaymentStatus_0, lastModifiedTime=LastModifiedTime_0, status=Status_0], orderID=OrderId_0], Order [buyerUserID=BuyerUserId_1, checkoutStatus=CheckoutStatus [eBayPaymentStatus=EBayPaymentStatus_1, lastModifiedTime=LastModifiedTime_1, status=Status_1], orderID=OrderId_1], Order [buyerUserID=BuyerUserId_2, checkoutStatus=CheckoutStatus [eBayPaymentStatus=EBayPaymentStatus_2, lastModifiedTime=LastModifiedTime_2, status=Status_2], orderID=OrderId_2]], paginationResult=PaginationResult [totalNumberOfEntries=10, totalNumberOfPages=5], timestamp=2007-12-10T16:12:55.184Z, version=539]
需要注意的是,在反序列化时,如果XML元素冗余,则会抛出UnknownFieldException异常,此时可以设置忽略未知元素:
xstream.ignoreUnknownElements();
如果要将XML元素中的属性与Java对象的字段对应,该怎么办呢?例如有XML元素:
Java类:
class Order{
private String orderID;
}
此时可以进行如下设置:
xstream.aliasAttribute(Order.class, "orderID", "id");