需要的jar包:xmlpull_1_0_5.jar,xstream-1.4.1.jar) 1、工具類XstreamUtil package com.learn.util; import com.thoughtworks.xstream.XStream; import com.thoughtworks ...
需要的jar包:xmlpull_1_0_5.jar,xstream-1.4.1.jar)
1、工具類XstreamUtil
package com.learn.util;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
*
* @ClassName: XstreamUtil.java
* @Description:
* @author: fengzf [email protected]
* @Date: 2016年12月6日
*
*/
publicclass XstreamUtil {
/**
* 將bean轉換為xml
* @param obj 轉換的bean
*@return bean轉換為xml
*/
publicstatic String objectToXml(Object obj) {
XStream xStream = new XStream();
// xstream使用註解轉換
xStream.processAnnotations(obj.getClass());
returnxStream.toXML(obj);
}
/**
* 將xml轉換為bean
* @param<T> 泛型
* @param xml 要轉換為bean的xml
* @param cls bean對應的Class
* @return xml轉換為bean
*/
publicstatic <T> T xmlToObject(String xml, Class<T> cls) {
XStream xstream = new XStream(new DomDriver());
// xstream使用註解轉換
xstream.processAnnotations(cls);
return (T) xstream.fromXML(xml);
}
}
2、Java普通實體類轉xml
實體類Message.java代碼
package com.learn.entity;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Response")
publicclass Message {
@XStreamAlias("returncode")
private String returnCode;
@XStreamAlias("returnmessage")
private String returnMessage;
@XStreamAlias("status")
privateintstatus;
@XStreamAlias("time")
private String reqTime;
public String getReturnCode() {
returnreturnCode;
}
publicvoid setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public String getReturnMessage() {
returnreturnMessage;
}
publicvoid setReturnMessage(String returnMessage) {
this.returnMessage = returnMessage;
}
publicint getStatus() {
returnstatus;
}
publicvoid setStatus(intstatus) {
this.status = status;
}
public String getReqTime() {
returnreqTime;
}
publicvoid setReqTime(String reqTime) {
this.reqTime = reqTime;
}
}
3、XML字元串轉實體
@XStreamAlias使用
一、 特點:
簡化的API;
無映射文件;
高性能,低記憶體占用;
整潔的XML;
不需要修改對象;支持內部私有欄位,不需要setter/getter方法
提供序列化介面;
自定義轉換類型策略;
二、 使用場景
Transport轉換
Persistence 持久化對象
Configuration 配置
Unit Tests 單元測試
Interface服務之間XML消息的交互