从JSON API获取嵌套值

时间:2019-01-07 12:32:49

标签: android json api

我有这个json代码

{
"status": "success",
"message": null,
"data": {
    "19": {
        "id": "19",
        "created": "2019-01-07 13:26:06",
        "createdby": 158,
        "touched": "2019-01-07 13:26:06",
        "touchedby": 158,
        "start": "2019-01-07",
        "end": "2019-01-08",
        "scoperole": 3,
        "scopecorp": 1,
        "body": "<p>test</p>",
        "language": "en"
    },
    "20": {
        "id": "20",
        "created": "2019-01-07 13:26:20",
        "createdby": 158,
        "touched": "2019-01-07 13:26:20",
        "touchedby": 158,
        "start": "2019-01-07",
        "end": "2019-01-08",
        "scoperole": 3,
        "scopecorp": 1,
        "body": "<p>test1</p>",
        "language": "en"
    }
},
"error": 0,
"line": 1515,
"debug": null

}

我想采用“ body” (测试,test1)的值。 我怎么能找到他们?我留下了我尝试查看的代码,但旁边只有 //不起作用。请问有什么想法吗?19,20也不同,所以我仅仅通过输入变量名就无法获得它们(例如JSONObject dataObj =new JSONObject(“ 数据”))

这是我的代码

 private void getJson() {
        URL obj = null;
        try {
            obj = new URL("https://gekon.technologypark.cz/api/v1/notification/");
            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("ApiSecret", LoginInfo.ApiSecret);
            conn.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            StringBuilder sb = new StringBuilder();
            String output;
            while ((output = br.readLine()) != null)
                sb.append(output);

            JSONObject jsonObj = new JSONObject(sb.toString());
            Log.d("test", "response" + jsonObj);

            JSONObject dataObj =new JSONObject("data");

            JSONObject dataObj19 =dataObj.getJSONObject("22");
            String body1 =dataObj19.getString("body");

            Log.d("test", "TEST ID" + body1);

            pushNotification(notifText);


        } catch (Exception e) {
            e.printStackTrace();
            Log.d("test", "PUSH CATCH" + e);

        }

    }

这是我的日志

  

** 2019-01-07 14:17:42.778 19712-19712 / ibm.gekon.vasileiosvlachakis.gekon D / alekos:   response {“ status”:“成功”,“ message”:null,“ data”:{“ 22”:{“ id”:“ 22”,“ created”:“ 2019-01-07   14:11:55“,”创建者“:158,”感动“:” 2019-01-07   14:11:55“,” touchedby“:158,”开始“:” 2019-01-07“,”结束“:” 2019-01-08“,” scoperole“:3,” scopecorp“:1,” body“:”

test22

“,” language“:” en“}},”错误“:0,” line“:1515,” debug“:null}

     

2019-01-07 14:17:42.785 19712-19712 / ibm.gekon.vasileiosvlachakis.gekon   D / alekos:PUSH CATCHorg.json.JSONException:类型的值数据   java.lang.String无法转换为JSONObject **

4 个答案:

答案 0 :(得分:2)

在这里您可以获得主体键的值。但这特定于19和20 JSON对象

   JSONObject dataObj = new 
   JSONObject(sb.toString()).getJSONObject("data");

    JSONObject dataObj19 =dataObj.getJSONObject("19");
    String body1 =dataObj19.getString("body");

    JSONObject dataObj20 =dataObj.getJSONObject("20");
    String body2 =dataObj20.getString("body");

如果Response在JSON data对象中有多个JSON对象,那么您需要一个循环来检索它

JSONObject dataObj =new JSONObject("data");
for(int i=0;i<dataObj.length();i++){
  JSONObject data =dataObj.getJSONObject(i);
        String body =data .getString("body");
}

答案 1 :(得分:0)

在JSON响应中,您的密钥应该始终是静态的,以便从密钥中获得特定的响应。

  

在这里检查数据JSONObject是否包含该密钥以进行错误处理。

    try {
       JSONObject jsonObj = new JSONObject(sb.toString());// assuming this as your main JSONObject
        if(jsonObj.has("data")){
            JSONObject dataObj =jsonObj.getJSONObject("data");
                if(dataObj.has("19")){
                    JSONObject json19 = dataObj.getJSONObject("19");

                    // Now here check if the json19 contains the key that you want.
                    if(json19.has("body")){
                        String valueBody = json19.getString("body"); // this will give you the value of body
                    }
                }
             }
            } catch (JSONException e) {
                e.printStackTrace();
            }

答案 2 :(得分:0)

JSONObject json = new JSONObject(sb.toString());
String statistics = json.getString("data");

for(Iteraor key=json.keys();key.hasNext();) {
    JSONObject keyValue = json.get(key.next());
     //now keyValue contains the 19,20 and so on... 
      String body1 =keyValue.getString("body");
      Log.d("test", "TEST ID" + body1);
}

Try this it might work.

答案 3 :(得分:0)

最好的方法是制作静态密钥,但是您可以获取所有密钥,然后为每个密钥获取价值

使用

 JSONObject dataObj =new JSONObject("data");

        Iterator<String> keys=dataObj.keys();

        while (keys.hasNext())
        {
            JSONObject currentObject =dataObj.getJSONObject(keys.next());
            String currentBody =currentObject.getString("body");

            Log.d("test", "TEST ID" + currentBody);

        }`