使用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);
- }
- }