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};
- JSONArray jsonArray = JSONArray.fromObject( boolArray );
- System.out.println( jsonArray );
- // prints [true,false,true]
- List list = new ArrayList();
- list.add( "first" );
- list.add( "second" );
- JSONArray jsonArray = JSONArray.fromObject( list );
- // prints ["first","second"]
- JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );
- // 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
- class MyBean{
- private String name = "json";
- private int pojoId = 1;
- private char[] options = new char[]{'a','f'};
- private String func1 = "function(i){ return this.options[i]; }";
- private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");
- // getters & setters
- ...
- }
- JSONObject jsonObject = JSONObject.fromObject( new MyBean() );
- System.out.println( jsonObject );
- /* prints
- {"name":"json","pojoId":1,"options":["a","f"],
- "func1":function(i){ return this.options[i];},
- "func2":function(i){ return this.options[i];}}
- */
當然還有從json對象轉到java對象,從xml轉到json,從json轉到xml這幾種轉化,也十分簡單,感興趣的話可以直接看這篇文章裡的例子:
[url]http://json-lib.sourceforge.net/usage.html[/url]
有兩個包共享一下: