本文共 2937 字,大约阅读时间需要 9 分钟。
XStream是一套简单实用的JAVA类库,它用于序列化对象和XML对象之间互相转换。由于XStream配置简单,灵活易用,因此在XML对象和JAVA对象序列化市场上有很大的空间。本文并不会对XStream的特性做详细介绍,只是以实例的方式演示XStream是多么的容易上手。
1.最新版的Jar包,上传到工程路径。
2.假设我们要将如下的XML对象转换为JAVA对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <? xml version = "1.0" encoding = "UTF-8" ?> < order > < orderId >201612150001</ orderId > < orderPrice >40.23</ orderPrice > < createDate >20161215180000</ createDate > < product > < productName >lvrouhuoshao</ productName > < productPrice >23</ productPrice > </ product > < product > < productName >鸡蛋灌饼</ productName > < productPrice >17.23</ productPrice > </ product > </ order > |
3.根据XML结构构建订单对象和产品对象
HiOrder.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package com.favccxx.favsoft.pojo; import java.util.List; public class HiOrder { private String orderId; private double orderPrice; private List<HiProduct> product; private String createDate; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this .orderId = orderId; } public double getOrderPrice() { return orderPrice; } public void setOrderPrice( double orderPrice) { this .orderPrice = orderPrice; } public List<HiProduct> getProduct() { return product; } public void setProduct(List<HiProduct> product) { this .product = product; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this .createDate = createDate; } } |
Product.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.favccxx.favsoft.pojo; public class HiProduct { private String productName; private double productPrice; public String getProductName() { return productName; } public void setProductName(String productName) { this .productName = productName; } public double getProductPrice() { return productPrice; } public void setProductPrice( double productPrice) { this .productPrice = productPrice; } } |
4.测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package com.favccxx.favsoft.main; import com.favccxx.favsoft.pojo.HiOrder; import com.favccxx.favsoft.pojo.HiProduct; import com.thoughtworks.xstream.XStream; public class MainOrder { public static void main(String[] args) { String xmlbody = "<?xml version='1.0' encoding='UTF-8'?><order><orderId>201612150001</orderId><orderPrice>40.23</orderPrice><createDate>2016-12-12 15:16:04</createDate><product><productName>lvrouhuoshao</productName><productPrice>23</productPrice></product><product><productName>鸡蛋灌饼</productName><productPrice>17.23</productPrice></product></order>" ; XStream xStream = new XStream(); xStream.alias( "order" , HiOrder. class ); xStream.alias( "product" , HiProduct. class ); xStream.addImplicitCollection(HiOrder. class , "product" ); HiOrder order = (HiOrder) xStream.fromXML(xmlbody); System.out.println(order.getOrderId()); } } |
5.运行上面测试类,输出订单的详细信息。只需简单的几步就可以将XML对象转换为JAVA对象,你看到这,是不是心痒的想要上手试一试呢?