在現在的開發當中,絕大多數引用阿里巴巴的fastjson。當然net.sf.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
二、引入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"));