1

I have this json code

{
"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

}

And i want to take the values of "body" (test,test1). How can i reach them?I left the code that i tried just to see it with //not working next to it.Any ideas please?Also the 19,20 are not the same so i'm not able to get them by just putting the name of a variable(ex JSONObject dataObj =new JSONObject ("data");

Here is my code

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

        }

    }

Here are my logs

**2019-01-07 14:17:42.778 19712-19712/ibm.gekon.vasileiosvlachakis.gekon D/alekos: response{"status":"success","message":null,"data":{"22":{"id":"22","created":"2019-01-07 14:11:55","createdby":158,"touched":"2019-01-07 14:11:55","touchedby":158,"start":"2019-01-07","end":"2019-01-08","scoperole":3,"scopecorp":1,"body":"

test22</p>","language":"en"}},"error":0,"line":1515,"debug":null}

2019-01-07 14:17:42.785 19712-19712/ibm.gekon.vasileiosvlachakis.gekon D/alekos: PUSH CATCHorg.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject**

Alex
  • 1,816
  • 5
  • 23
  • 39
  • Possible duplicate of [How to get elements of JSONObject?](https://stackoverflow.com/questions/24279958/how-to-get-elements-of-jsonobject) – Anmol Jan 07 '19 at 13:26

4 Answers4

2

Here you can get the value of body key. but this is specific for 19 and 20 JSON object

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

if Response has multiple JSON object inside data JSON object then you need a loop to retrieve it

JSONObject dataObj =new JSONObject("data");
for(int i=0;i<dataObj.length();i++){
  JSONObject data =dataObj.getJSONObject(i);
        String body =data .getString("body");
}
Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
0

In JSON response your key should always be static in order to get a particular response from the key.

Here check whether your data JSONObject contains that key or not for error handling.

    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();
            }
Savin Sharma
  • 769
  • 5
  • 22
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.

Anmol
  • 8,110
  • 9
  • 38
  • 63
0

best way is to make static key, but you can get all keys and then get value for each one

use

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

        }`
Ahmed.ess
  • 265
  • 3
  • 10