java解析多级Json中的数组

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);

 

posted @ 2020-06-05 18:45  HkGov  阅读(1409)  评论(0编辑  收藏  举报