java数据类型转换____Xstream框架对象和XML的转换
package com.cnse.convert.xstream;
/**
* 对象转xml的po
* @author God
*/
public class RespTextEntity {
// 接收方帐号(收到的OpenID)
private String ToUserName;
// 开发者微信号
private String FromUserName;
// 消息创建时间 (整型)
private long CreateTime;
// 消息类型(text/music/news)
private String MsgType;
// 位0x0001被标志时,星标刚收到的消息
private int FuncFlag;
// 回复的消息内容
private String Content;
//encap
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public long getCreateTime() {
return CreateTime;
}
public void setCreateTime(long createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public int getFuncFlag() {
return FuncFlag;
}
public void setFuncFlag(int funcFlag) {
FuncFlag = funcFlag;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
//微信的一个xml参数结构
package com.cnse.convert.xstream;
import java.io.Writer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
* @author Administrator
*
*/
public class XstreamUtil {
/**
* 文本消息对象转换成xml
* @param textMessage
* @return xml
*/
public static String ObjToXml(RespTextEntity textMessage) {
XStream xstream = new XStream();
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* 带Cdata包裹的
* @param textMessage
* @return
*/
public static String ObjToCDATAXml(RespTextEntity textMessage) {
XStream xCDATAstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
xCDATAstream.alias("xml", textMessage.getClass());
return xCDATAstream.toXML(textMessage);
}
//test
public static void main(String[] args) {
RespTextEntity r = new RespTextEntity();
r.setMsgType("Music");
r.setContent("this is teset ");
r.setFromUserName("zhangsan");
r.setCreateTime(123L);
r.setFuncFlag(1);
System.out.println("没有Cdata包裹的xml_:\n "+ObjToXml(r));
System.out.println("有CDATA包裹的xml__:\n "+ObjToCDATAXml(r));
}
}
//运行结果
//仍有大部分的平台使用者xml参数交互比较老的系统