Xstream 对象与xml 互转

需要

        jar : xtream.jar

 

第一步:工具类

public class XStreamWrapper {

 private XStream xstream;

 public XStreamWrapper() {
     xstream = new XStream();
        xstream.processAnnotations(obj1.class);
        xstream.processAnnotations(obj2.class);
 }
 
 public String toXML(Object obj){
  StringBuilder sb = new StringBuilder(XML_HEAD);
  sb.append(xstream.toXML(obj));
  return sb.toString();
 }
 
 @SuppressWarnings("unchecked")
    public <T> T fromXML(String xml, Class<T> clazz){
  if (xml == null || "".equals(xml)) {
   return null;
  }
  xstream.processAnnotations(clazz);
  return (T)xstream.fromXML(xml);
 }
 
 public XStream getXstream(){
  return xstream;
 }

 //xml格式头信息

 private static final String XML_HEAD = "<?xml version=\"1.0\" encoding=\"GBK\"?>\r\n";

}

 

 

第二步使用:

    xml数据String数据转Obj

    Obj1 obj1 = xstream.fromXML(responseXml, obj1.class);

 

    Obj转xml数据String

    xstream.toXML(obj1);

 

 

注意:

    obj中字段和xml中的标签一直,数据类型为String类型

 

    从obj转xml时候,obj中有多少个属性转为String xml时,每个属性代表每个标签

 

    从xml转obj,如果标签名和属性名不对应:com.thoughtworks.xstream.converters.ConversionException 异常

 

 

你可能感兴趣的:(xml)