XStream将XML转换为JAVA对象快速指南

前端之家收集整理的这篇文章主要介绍了XStream将XML转换为JAVA对象快速指南前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

XStream是一套简单实用的JAVA类库,它用于序列化对象和XML对象之间互相转换。由于XStream配置简单,灵活易用,因此在XML对象和JAVA对象序列化市场上有很大的空间。本文并不会对XStream的特性做详细介绍,只是以实例的方式演示XStream是多么的容易上手。


1.XStream官网下载最新版的Jar包,上传到工程路径。


2.假设我们要将如下的XML对象转换为JAVA对象。

<?xmlversion="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

packagecom.favccxx.favsoft.pojo;
importjava.util.List;
publicclassHiOrder{
privateStringorderId;
privatedoubleorderPrice;
privateList<HiProduct>product;
privateStringcreateDate;
publicStringgetOrderId(){
returnorderId;
}
publicvoidsetOrderId(StringorderId){
this.orderId=orderId;
}
publicdoublegetOrderPrice(){
returnorderPrice;
}
publicvoidsetOrderPrice(doubleorderPrice){
this.orderPrice=orderPrice;
}
publicList<HiProduct>getProduct(){
returnproduct;
}
publicvoidsetProduct(List<HiProduct>product){
this.product=product;
}
publicStringgetCreateDate(){
returncreateDate;
}
publicvoidsetCreateDate(StringcreateDate){
this.createDate=createDate;
}
}


Product.java

packagecom.favccxx.favsoft.pojo;
publicclassHiProduct{
privateStringproductName;
privatedoubleproductPrice;
publicStringgetProductName(){
returnproductName;
}
publicvoidsetProductName(StringproductName){
this.productName=productName;
}
publicdoublegetProductPrice(){
returnproductPrice;
}
publicvoidsetProductPrice(doubleproductPrice){
this.productPrice=productPrice;
}
}


4.测试代码

packagecom.favccxx.favsoft.main;
importcom.favccxx.favsoft.pojo.HiOrder;
importcom.favccxx.favsoft.pojo.HiProduct;
importcom.thoughtworks.xstream.XStream;
publicclassMainOrder{
publicstaticvoidmain(String[]args){
Stringxmlbody="<?xmlversion='1.0'encoding='UTF-8'?><order><orderId>201612150001</orderId><orderPrice>40.23</orderPrice><createDate>2016-12-1215:16:04</createDate><product><productName>lvrouhuoshao</productName><productPrice>23</productPrice></product><product><productName>鸡蛋灌饼</productName><productPrice>17.23</productPrice></product></order>";
XStreamxStream=newXStream();
xStream.alias("order",HiOrder.class);
xStream.alias("product",HiProduct.class);
xStream.addImplicitCollection(HiOrder.class,"product");
HiOrderorder=(HiOrder)xStream.fromXML(xmlbody);
System.out.println(order.getOrderId());
}
}


5.运行上面测试类,输出订单的详细信息。只需简单的几步就可以将XML对象转换为JAVA对象,你看到这,是不是心痒的想要上手试一试呢?

猜你在找的XML相关文章