一.org.json 解析器 (推薦使用,更適合于對(duì)象模型)
概述及例子: http://code.google.com/p/json-simple/
API: http://code.google.com/p/json-simple/
例(測(cè)試通過(guò),注意延遲加載問(wèn)題):
JSONArray jsona=new JSONArray();
JSONObject jsono=new JSONObject();
List<Author> l=authorDAO.findAll();
for(Author a:l){
jsono.put("author_num", a.getAuthorNam());
jsono.put("author_nam", a.getAuthorNum());
jsono.put("author_sex", a.getAuthorSex());
jsono.put("author_level", a.getLevel().getLevelNam());
jsono.put("author_department", a.getAuthorDepartment());
jsona.add(jsono.clone()); //jsono.clone()返回實(shí)例對(duì)象;jsono僅僅只是個(gè)指針
jsono.clear(); //必須清除內(nèi)容以備下次調(diào)用.
}
二.json-lib 解析器
(1)所需依賴的類文件
Json-lib requires (at least) the following dependencies in your classpath:
- jakarta commons-lang 2.3 //appach網(wǎng)站下載最新的
- jakarta commons-beanutils 1.7.0 //appach網(wǎng)站下載最新的
- jakarta commons-collections 3.2 //appach網(wǎng)站下載最新的
- jakarta commons-logging 1.1 //appach網(wǎng)站下載最新的
- ezmorph 1.0.4
詳見(jiàn): http://json-lib.sourceforge.net/
(2)下載JSON-LIB-2.2.1,并查找 ezmorph 1.0.4 文件
https://sourceforge.net/project/showfiles.php?group_id=171425
(3)舉例:
1
import net.sf.json.JSONArray;
2
3



4
5
boolean[] boolArray = new boolean[]
{true,false,true};
6
JSONArray jsonArray1 = JSONArray.fromObject( boolArray );
7
System.out.println( jsonArray1 );
8
// prints [true,false,true]
9
10
List list = new ArrayList();
11
list.add( "first" );
12
list.add( "second" );
13
JSONArray jsonArray2 = JSONArray.fromObject( list );
14
System.out.println( jsonArray2 );
15
// prints ["first","second"]
16
17
JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" );
18
System.out.println( jsonArray3 );
19
// prints ["json","is","easy"]