微信公众号xml数据解析之xstream
Posted 起岸星辰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号xml数据解析之xstream相关的知识,希望对你有一定的参考价值。
XStream是Java类库,用来将对象序列化成XML (JSON)或反序列化为对象。相对于jaxb来说要简单易用些,但是也会消耗更多的时间。下面我们看下如何使用。
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[CLICK]]></Event>
<EventKey><![CDATA[EVENTKEY]]></EventKey>
</xml>
创建实体类:ClickMenuEvent
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
import java.io.Serializable;
/**
* <p> 点击菜单拉取消息时的事件推送 </p>
*/
//这个是lombok的注解,加上后编译的class文件中会自动生成get set相关方法,记得安装lombok插件
"xml") //定义xml根节点 (
public class ClickMenuEvent implements Serializable {
//消息类型,event
"MsgType")//xml中的名称和实体类中名称进行映射 (
private String msgType;
//事件类型,CLICK
"Event") (
private String event;
//开发者 微信号
"ToUserName") (
private String toUserName;
//发送方帐号(一个OpenID)
"FromUserName") (
private String fromUserName;
//消息创建时间 (整型)
"CreateTime") (
private String createTime;
//事件KEY值,与自定义菜单接口中KEY值对应
"eventKey") (
private String EventKey;
}
开始解析:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
public class MyTest {
public static void main(String[] args) {
String xml = "<xml>" +
"<ToUserName><![CDATA[toUser]]></ToUserName>" +
"<FromUserName><![CDATA[FromUser]]></FromUserName>" +
"<CreateTime>123456789</CreateTime>" +
"<MsgType><![CDATA[event]]></MsgType>" +
"<Event><![CDATA[CLICK]]></Event>" +
"<EventKey><![CDATA[EVENTKEY]]></EventKey>" +
"</xml>";
XStream xStream = new XStream(new XppDriver(new NoNameCoder()));
xStream.processAnnotations(ClickMenuEvent.class);
//解决提示 Security framework of XStream not initialized, XStream is probably vulnerable.
xStream.allowTypes(new Class[]{ClickMenuEvent.class});
ClickMenuEvent pojo = (ClickMenuEvent) xStream.fromXML(xml);
System.out.println(pojo.toString());
}
}
同样使用上面的实体对象ClickMenuEvent
public static void main(String[] args) {
XStream xStream = new XStream(new XppDriver(new NoNameCoder()));
xStream.processAnnotations(ClickMenuEvent.class);
ClickMenuEvent pojo = new ClickMenuEvent();
pojo.setCreateTime("9876543210");
pojo.setEvent("CLICK");
pojo.setEventKey("123456");
pojo.setMsgType("event");
pojo.setFromUserName("张三");
pojo.setToUserName("李四");
String xml = xStream.toXML(pojo);
System.out.println(xml);
}
转换后的结果
<xml>
<MsgType>event</MsgType>
<Event>CLICK</Event>
<ToUserName>李四</ToUserName>
<FromUserName>张三</FromUserName>
<CreateTime>9876543210</CreateTime>
<eventKey>123456</eventKey>
</xml>
以上是关于微信公众号xml数据解析之xstream的主要内容,如果未能解决你的问题,请参考以下文章