1. json-lib是一個java類庫,提供將Java對象,包括beans, maps, collections, java arrays and XML等轉換成JSON,或者反向轉換的功能。java
2. json-lib 主頁 : http://json-lib.sourceforge.net/json
find-jar(用來查找jar包):http://www.findjar.com/index.x數組
3.執行環境app
須要如下類庫支持測試
4.測試this
package com.bipaas.utility;.net
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;code
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;對象
public class TransJSON {blog
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//List集合轉換成json代碼
List list = new ArrayList();
list.add("first");
list.add("second");
JSONArray json1 = JSONArray.fromObject(list);
System.out.println(json1+"………………json1");
//Map集合轉換成json代碼
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 json2 = JSONObject.fromObject(map);
System.out.println(json2+"………………json2");
//Bean轉換成json代碼
// JSONObject jsonObject = JSONObject.fromObject(new JSONBean());
//數組轉換成json代碼
boolean[] boolArray = new boolean[]{true,false,true};
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
System.out.println(jsonArray1+"………………jsonArray1");
String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
JSONObject json3 = JSONObject.fromObject( json );
System.out.println(json3+"………………json3");
String json4 = "{bool:true,integer:1,string:\"json\"}";
JSONObject jsonObject3 = JSONObject.fromObject( json4 );
System.out.println(json4+"………………json4");
//通常數據轉換成json代碼
JSONArray jsonArray2 = JSONArray.fromObject("['json','is','easy']");
System.out.println(jsonArray2+"………………jsonArray2");
}
}
5.執行結果
log4j:ERROR No appender named [console] could be found. ["first","second"]………………json1 {"arr":["a","b"],"int":1,"name":"json","func":function(i){return this.arr[i];},"bool":true}………………json2 [true,false,true]………………jsonArray1 {"name":"json","bool":true,"int":1,"double":2.2,"func":function(a){ return a; },"array":[1,2]}………………json3 {bool:true,integer:1,string:"json"}………………json4 ["json","is","easy"]………………jsonArray2