1. 程式人生 > >net.sf.json與fastjson兩種jar包的使用

net.sf.json與fastjson兩種jar包的使用

先說清楚:這兩種方式是進行json解析的兩種不同的方式而已,哪一種都可以。

一、引入net.sf.json包

首先用net.sf.json包,當然你要匯入很多包來支援commons-beanutils-1.7.0.jar commons-collections-3.1.jar commons-lang-2.5.jar commons-logging.jar ezmorph-1.0.3.jar json-lib-2.1-jdk15.jar,自己百度下載吧

然後使用方法:

json串:{\"code\":0,\"msg\":\"成功\",\"data\":{\"template\":{\"templateId\":23,\"code\":\"redmine\",\"type\":0,\"status\":0,\"nodeName\":\"會員期限即將到期\",\"detail\":\"1個月\",\"content\":\"您的會員...\"}}}

呼叫:

Map<String,String> dto = new HashMap<String,String>();

dto.put("code", app.getCode());

xxService.getxx(JSONObject.fromObject(dto).toString());

解析:

JSONObject jsonObject = JSONObject.fromObject(msgContent);  

JSONObject o2=JSONObject.fromObject(jsonObject.get("data")); 

JSONObject o3=JSONObject.fromObject(o2.get("template"));

(String)o3.get("content")

好了,你就獲得到最底層的內容了

 

如果是json串中使用了[]的這種就需要用到JSONArray了,這篇博文寫的不錯http://blog.csdn.net/qq_22792489/article/details/51111890

有的時候你只是再原來的基礎上改程式碼,但是別人用的是com.alibaba.fastjson包,沒辦法,只能相容了唄,那就用com.alibaba.fastjson吧,只是方法名不一樣,功能實現就行

 

二、引入com.alibaba.fastjson包

呼叫:

Map<String,String> dto = new HashMap<String,String>();

        dto.put("code", "haha");

        System.out.println(JSONObject.toJSON(dto).toString());

解析:

JSONObject jsonObject = JSONObject.parseObject(result);         

JSONObject o2=JSONObject.parseObject((String) jsonObject.getString("data")); 

JSONObject o3=JSONObject.parseObject((String) o2.getString("template")); 

System.out.println((String) jsonObject.getString("data"));

System.out.println((String) o2.getString("template"));

System.out.println((String) o3.getString("content"));

 最底層的模板內容也有了,大功告成!

**歡迎關注我的個人公眾號:we-aibook,裡面有相關技術文章分享,專案架構,知識星球,技術交流群,不定期進行抽獎送書活動喲!**