JSON 即 JavaScript Object Natation,它是一種輕量級的數據交換格式,非常適合於服務器與 JavaScript 的交互。本文將快速講解 JSON 格式,並通過代碼示例演示如何分別在客戶端和服務器端進行 JSON 格式數據的處理。
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
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher錯誤
是因為沒有導入ezmorph.jar文件或版本不對。
java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap錯誤
是因為沒有導入commons-collections.jar文件或版本不對。
Java代碼轉換成json代碼
1. List集合轉換成json代碼
List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list );
2. 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; }"); JSONObject json = JSONObject.fromObject(map);
3. Bean轉換成json代碼
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4. 數組轉換成json代碼
boolean[] boolArray = new boolean[] { true, false, true }; JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. 一般數據轉換成json代碼
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
6. beans轉換成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);