XStream 框架使用

    技术2022-05-20  55

    XStream 框架实现xml与java对象序列化与反序列化,同时支持java对象与json序列化,反序列化,但是对于json序列化有两种驱动方式

    先举例说明:

    java对象,当然支持复杂对象了

    public class Message { private String mobile; private String type; private String content; public Message(){ } public Message(String mobile, String type, String content) { this.mobile = mobile; this.type = type; this.content = content; } /** * @return the mobile */ public String getMobile() { return mobile; } /** * @param mobile the mobile to set */ public void setMobile(String mobile) { this.mobile = mobile; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the content */ public String getContent() { return content; } /** * @param content the content to set */ public void setContent(String content) { this.content = content; } }

     

     

    测试类

    import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.xml.DomDriver; public class Test { /** * @param args */ public static void main(String[] args) { Message msg = new Message("15810957053","0","从火车站到博物馆怎么走"); XStream xStream = new XStream(new DomDriver()); xStream.alias("message", com.sohu.sms.bus.Message.class); String xml = xStream.toXML(msg); System.out.println(xml); Message o = (Message)xStream.fromXML(xml); System.out.println(o.getContent()); System.out.println(o.getType()); System.out.println(o.getMobile()); XStream xstreamJson = new XStream(new JettisonMappedXmlDriver()); xstreamJson.setMode(XStream.NO_REFERENCES); xstreamJson.alias("message", com.sohu.sms.bus.Message.class); String json = xstreamJson.toXML(msg); System.out.println(json); Message j = (Message)xstreamJson.fromXML(json); System.out.println(j.getContent()); } }

     

     

    XStream xstreamJson = new XStream(new JettisonMappedXmlDriver());

    该JettisonMappedXmlDriver  JSON驱动器需要Jettison.jar支持,可以到官方网站下载,该驱动器支持json序列化与反序列化

    XStream xstreamJson = new XStream(new HierarchicalStreamDriver());

     该HierarchicalStreamDriver  JSON驱动器不需要第三方jar依赖,但是仅支持java对象序列化为json,不支持反序列化

     

     

    对于XStream 框架简易,相比重量级框架,更容易上手,性能目前还没有比较测试,希望有时间测试下目前主流xml序列化框架的性能

    进行简单总结。

     


    最新回复(0)