之前一直用的是官网上的库:http://www.json.org/java/index.html
个人体验,这个库的毛病挺多的,比如在将JSONObject转换成String的过程中会产生大量的临时性的String对象(因为没用StringBuffer),更郁闷的一个问题是,它可以很容易的将Java的某个对象序列化成JSON格式的字符串,比如:
MyObject myobj = new MyObject(); JSONObject jsonobj = new JSONObject(myobj); String jsonstr = jsonobj.toString();但是,你没有办法反序列化回来: jsonstr -> myobj如果想得到这个效果,就只能很笨的自己动手将myobj的那些变量一个个从jsonstr中提取出来,然后重新拼装。
今天在网上搜了一下,才发现基于JAVA的JSON库原来还有很多,而且许多都要强于官网版。
本文介绍的是其中的一个: google-gson(Gson)
Link: http://code.google.com/p/google-gson/
之所以用它是因为这个库能够实现反序列化的功能,而且代码超简单:
序列化:
MyObject myobj = new Gson().fromJson(jsonstr, MyObject.class);
最后,附上stackoverflow上关于几个JSON库的比较:
JSONLib is awsesome as a core JSON library when you just want to process all elements of a JSON.
FlexJSON shines with its deepSerialize method that can properly handle serializing all get methods presented in a bean obtained from Hibernate (lazy loaded).
ContainerManifest cm = cmDAO.read( cmId ); String cmJson = new JSONSerializer().deepSerialize( cm );Gson seems to be the best API to use when you want to convert a json to a Java class. Other API only call set methods on the high level classes in the bean structure. If you have a deep bean structure, everything else will be implemented with dyna beans. Causes havoc elsewhere. Gson fully populates all low level values by calling all set methods for all data found in the JSON.Gson gson = new Gson(); ContainerManifest cm = gson.fromJson( json, ContainerManifest.class );