对象与xml,json互换的几个工具包

gson: 将json对象转为java对象.
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

...

List<Article> article = new ArrayList<Article>();
GsonBuilder gson = new GsonBuilder();
gson.setDateFormat("yyyy-MM-dd");
String jsonString = "[{},{}]";
article = 
gson.create().fromJson(jsonString,new TypeToken<List<Article>>(){}.getType());

...


这样的简单实现能够保证提供的jsonString被指定为Article类型的ArrayList被gson包转换成指定的ArrayList<Article>;

gson API: http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/Gson.html




XStream:
提供几个XStream的学习页面地址:
http://www.ibm.com/developerworks/cn/xml/x-xstream/  (developerWorks 中国)

http://unmi.cc/xstream-javabean-xml-json   (Unmi同志的BLOG)

XStream 去除生成的XML节点的class="list"

使用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.



貌似XMLEncoder XMLDecoder也挺好用的。JDK里面内置的。处理的方式不一样,是通过序列化对象输出XML格式的方式而已

提供gson-1.5.jar,xstream-1.3.1.jar


你可能感兴趣的:(xml,json,bean,SVN,Google)