Xml字符串和Java对象转换利器——XStream

前端之家收集整理的这篇文章主要介绍了Xml字符串和Java对象转换利器——XStream前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Maven配置:
<dependency>
	<groupId>com.thoughtworks.xstream</groupId>
	<artifactId>xstream</artifactId>
	<version>1.4.7</version>
</dependency>

实体类见博客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<Class<?>> 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<Order> orders = new ArrayList<Order>();
		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})));
	}
}
结果:
--------序列化---------
<GetOrdersResponse>
  <timestamp>2007-12-10T16:12:55.184Z</timestamp>
  <ack>Success</ack>
  <version>539</version>
  <build>e539_core_Bundled_5642307_R1</build>
  <paginationResult>
    <totalNumberOfEntries>10</totalNumberOfEntries>
    <totalNumberOfPages>5</totalNumberOfPages>
  </paginationResult>
  <orderArray>
    <Order>
      <orderID>OrderId_0</orderID>
      <checkoutStatus>
        <eBayPaymentStatus>EBayPaymentStatus_0</eBayPaymentStatus>
        <lastModifiedTime>LastModifiedTime_0</lastModifiedTime>
        <status>Status_0</status>
      </checkoutStatus>
      <buyerUserID>BuyerUserId_0</buyerUserID>
    </Order>
    <Order>
      <orderID>OrderId_1</orderID>
      <checkoutStatus>
        <eBayPaymentStatus>EBayPaymentStatus_1</eBayPaymentStatus>
        <lastModifiedTime>LastModifiedTime_1</lastModifiedTime>
        <status>Status_1</status>
      </checkoutStatus>
      <buyerUserID>BuyerUserId_1</buyerUserID>
    </Order>
    <Order>
      <orderID>OrderId_2</orderID>
      <checkoutStatus>
        <eBayPaymentStatus>EBayPaymentStatus_2</eBayPaymentStatus>
        <lastModifiedTime>LastModifiedTime_2</lastModifiedTime>
        <status>Status_2</status>
      </checkoutStatus>
      <buyerUserID>BuyerUserId_2</buyerUserID>
    </Order>
  </orderArray>
</GetOrdersResponse>
----------反序列化---------
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元素:

<Order id="123"/>
Java类:
class Order{
        private String orderID;
}
此时可以进行如下设置:
xstream.aliasAttribute(Order.class,"orderID","id");
原文链接:https://www.f2er.com/xml/295947.html

猜你在找的XML相关文章