使用FastJson解析Json數據

fastjson 是一個性能極好的用 Java 語言實現的 JSON 解析器和生成器,來自阿里巴巴的工程師開發。

主要特點

  • 快速FAST (比其它任何基於Java的解析器和生成器更快,包括jackson

  • 強大(支持普通JDK類包括任意Java Bean Class、Collection、Map、Date或enum)

  • 零依賴(沒有依賴其它任何類庫除了JDK)


一 、生成Json:
JavaBean、List<JavaBean>、List<String>、List<Map<String,Object>>
String jsonString = JSON.toJSONString(obj);

二、解析Json:
(1)JavaBean
Class class= JSON.parseObject(jsonString, Class.class);
(2)List<JavaBean>
List<Class> class=JSON.parseArray((jsonString, Class.class);
(3)List<String>
List<String> listString = JSON.parseArray(jsonString, String.class);
(4)List<Map<String,Object>>
List<Map<String, Object>> listMap = JSON.parseObject(jsonString, new TypeReference<List<Map<String,Object>>>(){});

現有這樣的json數據:

{"totalRecords":2615,
"result":{"code":"200","status":"success"},
"list":[{"unuAbnId":"0bcd930f-014c-1000-e003-5f160a0d0114",
"entNo":"1c2e4ca8-00fa-1000-e000-74590a76bf0f",
"regNO":"442000600169663",
"entName":"x",
"entType":"9910  ",
"speCause":"3",
"abnTime":"Mar 13, 2015 12:00:00 AM",
"decOrg":"442020",
"entNameUrl":"<a href=\".. ",
"auditingFileNo":"15000684990326",
"abnormalID":"fd74013d-014b-1000-e00a-72970a0d0114"},{...},{...},...],
"pageNo":1,
"pageSize":8,
"url":"main/abnInfoPage",
"selList":[{"unuAbnId":"0bcd930f-014c-1000-e003-5f0f0a0d0114",
"entNo":"16da9629-0131-1000-e005-3effc0a803a8",
"regNO":"442000602187424",
"entName":"x",
"entType":"9910  ",
"speCause":"3",
"abnTime":"Mar 13, 2015 12:00:00 AM",
"decOrg":"442020",
"entNameUrl":"<a href=\"..\">",
"auditingFileNo":"15000684990319",
"abnormalID":"fd74013d-014b-1000-e00a-72970a0d0114"},{...},{...},...],
"topPageNo":1,
"totalPages":327,
"previousPageNo":0,
"nextPageNo":2,
"bottomPageNo":327
}
其中list含有2615條數據,selList含有8條數據,目標是提取selList中entNameUrl的鏈接(不含a href=)
 外層是JSONObject,裏面的list和selList是JSONArrary,再裏面是JSONObject。其中的result也是JSONObject
JSONObject jsonObj = JSON.parseObject(rawText);
JSONArray result = jsonObj.getJSONArray("selList");
List<Link> links= JSON.parseArray(result.toJSONString(),Link.class);
其中Link類中要有entNameUrl這個屬性,並且setter和getter方法。
在setter方法中可以進一步進行處理
 public void setEntNameUrl(String entNameUrl) {
     this.entNameUrl =Html.create(entNameUrl).links().get();
}
這裏使用了自定方法,其功能就是取出字符串中的鏈接。

Link類中可以包含abnTime、entName、regNO等屬性和對應的getter和setter方法,FastJson能自動映射。

通過下面的方法也可以處理:
JSONObject jsonObj = new JSONObject(rawText);
JSONArray jsonArray = result .getJSONArray("selList");
for (int i = 0; i < jsonArray.length; i++) {
 
}




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