Java之——XStream 去除生成的XML節點的class="list"
阿新 • • 發佈:2019-01-04
使用XStream轉換BEAN到XML得時候,由於bean裡面有個Collection tasks屬性,結果解析出來的節點裡面有class="list"屬性:<tasks class="list">,很不好看,後來看到一封mail後知道,原來屬性Collection tasks初始化成了ArrayList,XStream發現定義的型別和初始化型別不一樣就會增加class="list",屬性;只要把tasks改成ArrayList tasks就可以了,class="list"不再出現。以下是原文:
> XStream writes a class attribute if the member type does not match the
> type of the object instance stored in this field. Otherwise it is not
> necessary to deserialize the objects again. In your case the member seems
> of type collection, but you use actually an ArrayList? You may set the
> default implementation for Collection to be an ArrayList.
另一種方式:
public class XMLUtil { private static final XStream xStream = new XStream(); // 將物件轉為XML字串 public static <T> String toXML(T obj) { Class<?> cls = obj.getClass(); xStream.alias(cls.getSimpleName().toLowerCase(), cls); [color=red]xStream.aliasSystemAttribute(null, "class"); // 去掉 class 屬性[/color] return xStream.toXML(obj); } // 將XML字串轉為物件 @SuppressWarnings({"unchecked"}) public static <T> T fromXML(String xml) { return (T) xStream.fromXML(xml); } }