天天看點

json-lib 研究

                                                                  JSON-LIB研究

         首先聲明,這篇文章基本屬于翻譯的東西,如果你對原文感興趣的話可以通路[url]http://json-lib.sourceforge.net/[/url]這個網址,上面很詳細,本人隻是斷章取義,快速應用這個東東而已.

         最近做項目,前台要使用jquery+json來實作 js部分的編碼,json就不多說了,目前很流行的ajax調用方式,本文關注的是:如何将javabean轉化成json的資料格式。總所周知,json的資料格式如下所示:

        {"name":"huqilong","age":18,"province":"henan"}.................

如果總是拿字元串來拼湊,就會成為一件很惡心的事情,于是google一下,找到了這個東西"Json-Lib".

        一:安裝,在剛才的那個網址下載下傳下來json-lib.jar ,添加到你的工程下即可(注意它有幾個依賴包,還好都是常用的jar包)。、

       二:使用 JSONArray

 JSONArray的靜态方法fromObject()可以直接将java的Array 或者Collection類型轉換成Json資料格式,如下:

     boolean[] boolArray = new boolean[]{true,false,true};   

  1. JSONArray jsonArray = JSONArray.fromObject( boolArray );   
  2. System.out.println( jsonArray );   
  3. // prints [true,false,true]  
  1. List list = new ArrayList();   
  2. list.add( "first" );   
  3. list.add( "second" );   
  4. JSONArray jsonArray = JSONArray.fromObject( list );   
  5. // prints ["first","second"]  
  1. JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );   
  2. // prints ["json","is","easy"]  

     三:将javaBean和HashMap轉化成Json對象

            MAP

            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 jsonObject = JSONObject.fromObject( map );   

           System.out.println( jsonObject );   

           // prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i)  { return this.arr[i]; }]  

       JAVABEAN

  1. class MyBean{   
  2.    private String name = "json";   
  3.    private int pojoId = 1;   
  4.    private char[] options = new char[]{'a','f'};   
  5.    private String func1 = "function(i){ return this.options[i]; }";   
  6.    private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");   
  7.    // getters & setters   
  8.    ...   
  9. }   
  10. JSONObject jsonObject = JSONObject.fromObject( new MyBean() );   
  11. System.out.println( jsonObject );   
  12. /* prints  
  13.   {"name":"json","pojoId":1,"options":["a","f"],  
  14.   "func1":function(i){ return this.options[i];},  
  15.   "func2":function(i){ return this.options[i];}}  
  16. */  

當然還有從json對象轉到java對象,從xml轉到json,從json轉到xml這幾種轉化,也十分簡單,感興趣的話可以直接看這篇文章裡的例子:

[url]http://json-lib.sourceforge.net/usage.html[/url]

有兩個包共享一下:

繼續閱讀