json-lib简介
JSON-lib这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
下载地址:http://json-lib.sourceforge.net
还要需要的第3方包:
org.apache.commons(3.2以上版本)
org.apache.oro
net.sf.ezmorph(ezmorph-1.0.4.jar)
nu.xom
How to use json-lib
Using the JSONSerializerWorking with arrays and collections
Working with objects
Working with XML
Using the JSONSerializer
JSONSerializer can transform any java object to JSON notation and back with a simple and clean interface, leveraging all the builders in JSONObject and JSONArray. To transform a java obect into JSON use JSONSerializer.toJSON(). To transform a valid JSON value (by JSON, I mean an Object implementing that interface), use toJava(). The last method is an instance method because the serializer needs special configuration to transform a JSON value to a bean class, array, List or DynaBean.
Working with arrays and collections
The simplest way to create a JSONArray from a java array or collection is through the static factory methods from JSONArray. JSONArray.fromObject() will inspect its parameter and call the correct factory or constructor.
Examples:
- boolean[] boolArray = new boolean[]{true,false,true};
- JSONArray jsonArray = JSONArray.fromObject( boolArray );
- System.out.println( jsonArray );
- // prints [true,false,true]
- List list = new ArrayList();
- list.add( "first" );
- list.add( "second" );
- JSONArray jsonArray = JSONArray.fromObject( list );
- System.out.println( jsonArray );
- // prints ["first","second"]
推荐文章 |
