JSON-lib的應用

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.html

http://json-lib.sourceforge.net/

http://ezmorph.sourceforge.net/

http://morph.sourceforge.net/

http://www.docjar.com/

中下載到。

出現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);

 

7.json軟成對象,jsonString={id:12;id=44}

JSONObject json=JSONObject.fromObject(jsonString);
        Object o=json.get(key);
        List<String> ls=new ArrayList<String>();
        if(o.getClass().equals(JSONArray.class)){
            JSONArray o2=(JSONArray)o;           
            for(Object obj:o2){
                ls.add(obj.toString());                   
            }
        }else{
            ls.add(o.toString());
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章