來源:北大青鳥飛迅校區(qū)|發(fā)布時(shí)間:2013-04-28 08:38:27
JSON是一種很簡潔很重要的數(shù)據(jù)格式,通常用來交換傳輸數(shù)據(jù),廣泛使用于JavaScript技術(shù)中,并逐漸在各種流行編程語言中火了起來。在Java中也有一個(gè)JSON的庫,用來重要作用就是Java對象與JSON、XML數(shù)據(jù)的相互轉(zhuǎn)換,有著重要的應(yīng)用。
環(huán)境:JDK5 , json-lib-2.3-jdk15
所依賴的包:json-lib-2.3-jdk15.jar,commons-collections.jar,commons- lang.jar,commons-logging.jar,commons-beanutils.jar,ezmorph-1.0.6.jar,xom-1.1.jar
java中各種類型所對應(yīng)的json格式:
1.數(shù)組或集合--》JSON串
public static void test1() {
System.out.println(“------------數(shù)組或集合--》JSON串----------”);
boolean[] boolArray = new boolean[]{true, false, true};
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
System.out.println(jsonArray1);
//輸出格式: [true,false,true]
List list = new ArrayList();
list.add(“first”);
list.add(“second”);
JSONArray jsonArray2 = JSONArray.fromObject(list);
System.out.println(jsonArray2);
//輸出格式: [“first”,“second”]
JSONArray jsonArray3 = JSONArray.fromObject(“[‘json’,‘is’,‘easy’]”);
System.out.println(jsonArray3);
//輸出格式: [“json”,“is”,“easy”]
}
2.Object|Map--》JSON串
public static void test2() {
System.out.println(“------------Object|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 jsonObject1 = JSONObject.fromObject(map);
System.out.println(jsonObject1);
//輸出格式: {“func”:function(i){ return this.arr[i]; },“arr”:[“a”,“b”],“int”:1,“bool”:true,“name”:“json”}
JSONObject jsonObject2 = JSONObject.fromObject(new MyBean());
System.out.println(jsonObject2);
//輸出格式: {“func1”:function(i){ return this.options[i]; },“func2”:function(i){ return this.options[i]; },“name”:“json”,“options”:[“a”,“f”],“pojoId”:1}
全程面授,不高薪都難
申請成功后,我們將在24小時(shí)內(nèi)與您聯(lián)系
招生熱線: 4008-0731-86 / 0731-82186801
學(xué)校地址: 長沙市天心區(qū)團(tuán)結(jié)路6號
Copyright © 2006 | 湖南大計(jì)信息科技有限公司 版權(quán)所有
湘ICP備14017520號-3