JSON-lib这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
下载地址:
还要需要的第3方包:
org.apache.commons(3.2以上版本)
org.apache.oro
net.sf.ezmorph(ezmorph-1.0.4.jar)
nu.xom
1、List
Java代码
boolean[] boolArray = newboolean[]{true,false,true}; JSONArray jsonArray1 = JSONArray.fromObject( boolArray ); System.out.println( jsonArray1 ); // prints [true,false,true] List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list ); System.out.println( jsonArray2 ); // prints ["first","second"] JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" ); System.out.println( jsonArray3 ); // prints ["json","is","easy"] boolean[] boolArray = new boolean[]{true,false,true}; JSONArray jsonArray1 = JSONArray.fromObject( boolArray ); System.out.println( jsonArray1 ); // prints [true,false,true] List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list ); System.out.println( jsonArray2 ); // prints ["first","second"] JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" ); System.out.println( jsonArray3 ); // prints ["json","is","easy"]2、Map
Java代码
Map map = new HashMap(); map.put( "name", "json" ); map.put( "bool", Boolean.TRUE ); map.put( "int", new Integer(1) ); map.put( "arr", new String[]{"a","b"} ); map.put( "func", "function(i){ return this.arr[i]; }" ); JSONObject json = JSONObject.fromObject( map ); System.out.println( json ); //{"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"name":"json","bool":true} Map map = new HashMap(); map.put( "name", "json" ); map.put( "bool", Boolean.TRUE ); map.put( "int", new Integer(1) ); map.put( "arr", new String[]{"a","b"} ); map.put( "func", "function(i){ return this.arr[i]; }" ); JSONObject json = JSONObject.fromObject( map ); System.out.println( json ); //{"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"name":"json","bool":true}3、BEAN