使用JSON的方法
JSON 即 JavaScript Object Natation,它是一種輕量級(jí)的數(shù)據(jù)交換格式,非常適合于服務(wù)器與 JavaScript 的交互。本文將快速講解 JSON 格式,并通過(guò)代碼示例演示如何分別在客戶端和服務(wù)器端進(jìn)行 JSON 格式數(shù)據(jù)的處理。
Json必需的包
commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.2.3-jdk13.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
以上包可以從
http://commons.apache.org/index.htmlhttp://json-lib.sourceforge.net/http://ezmorph.sourceforge.net/http://morph.sourceforge.net/http://www.docjar.com/中下載到。
出現(xiàn)java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher錯(cuò)誤是因?yàn)闆](méi)有導(dǎo)入ezmorph.jar文件或版本不對(duì)。
出現(xiàn)java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap錯(cuò)誤是因?yàn)闆](méi)有導(dǎo)入commons-collections.jar文件或版本不對(duì)。
Java代碼轉(zhuǎn)換成json代碼
1. List集合轉(zhuǎn)換成json代碼
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
2. Map集合轉(zhuǎn)換成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 json = JSONObject.fromObject(map);
3. Bean轉(zhuǎn)換成json代碼
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4. 數(shù)組轉(zhuǎn)換成json代碼
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. 一般數(shù)據(jù)轉(zhuǎn)換成json代碼
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
6. beans轉(zhuǎn)換成json代碼
List list = new ArrayList();
JsonBean2 jb1 = new JsonBean2();
jb1.setCol(1);
jb1.setRow(1);
jb1.setValue("xx");
JsonBean2 jb2 = new JsonBean2();
jb2.setCol(2);
jb2.setRow(2);
jb2.setValue("");
list.add(jb1);
list.add(jb2);
JSONArray ja = JSONArray.fromObject(list);