1. 程式人生 > >Xstream 物件與xml 互轉

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 異常