import org.json.JSONArray; import org.json.JSONObject; public class Test { public static void main(String[] args) throws Exception{ //原始String類型json String aaa = "{\"code\":\"\",\"errorCode\":\"200\",\"errorContext\":null,\"message\":\"\\r\\n\",\"resultObject\": {\"listDataMap\":[{\"successRuleCount\":22,\"failRuleCount\":0,\"checkSuccess\":\"true\",\"checkUrl\":\"http://www.baidu.com\"},{}]},\"success\":true}"; //先轉成JSONObject,取出第一層resultObject中的內容 JSONObject resultObject = (JSONObject)getValue(new JSONObject(aaa),"resultObject"); //這里因為listDataMap中是數組的形式,所以要轉成JSONArray來取 JSONArray listDataMap = (JSONArray)getValue(resultObject,"listDataMap"); //取出數組中第一個值里面所需要的key對應的value System.out.println(getValue(listDataMap.getJSONObject(0),"checkSuccess")); System.out.println(getValue(listDataMap.getJSONObject(0),"checkUrl")); } public static Object getValue(JSONObject json, String key){ if(json ==null){ return null; }else { if(json.isNull(key)){ return null; }else { return json.get(key); } } } }
方法二
解析普通json
result { "success":"true", "returnAddress":"123" } JSONObject jsonObject=JSON.parseObject(result); //轉換成object jsonObject.getString("returnAddress") //獲取object中returnAddress字段;
result { "success":"true", "data":{ "shop_uid":"123" } } JSONObject shop_user =JSON.parseObject(result); JSON.parseObject(shop_user.getString("data")).getString("shop_uid")
解析數組型json
result { "success":"true", "data":[{ "shop_uid":"123" }, { "shop_name":"張三" }] } JSONArray detail = JSON.parseArray(result); for (int i=0; i<detail.size();i++){ if(detail.get(i)!=null||!detail.get(i).equals("")){ JSONArray detailChild =detail.getJSONArray(i); if(detailChild.getInteger(1)>Integer.valueOf(ship.get("shiptime").toString())){ ship.put("shiptime",detailChild.getInteger(1)); ship.put("desc",detailChild.getString(0)); } } }
JSON轉javaBean
JSONobject=>javaBean JSONObject contentChild = contentsArray.getJSONObject(i); QCCustomerScore.CustomerCore customerCore = JSON .toJavaObject(contentChild, QCCustomerScore.CustomerCore.class);