Search code examples
androidjsonjsonexception

JSONObject parsing error when there is no value


I have a JSON which looks like this:

{
"notifications": {
    "0": {
        "id": "27429",
        "uID": "6967",
        "text": "Text 1"
    },
    "1": {
        "id": "27317",
        "uID": "6967",
        "text": "Text 2"
    },
    "2": {
        "id": "27315",
        "uID": "6967",
        "text": "Text 3"
    },
    "3": {
        "id": "27314",
        "uID": "6967",
        "text": "Text 4"
    },
    "4": {
        "id": "27312",
        "uID": "6967",
        "text": "Text 5"
    }
}
}

I'm taking out "text" string from the response, for this my code looks like this:

JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");

int maxlimit = 4;

for (int i = 0; i < maxlimit; i++) {
    JSONObject jNotification0 = jSearchData.getJSONObject("" + i + "");

    String text = jNotification0.getString("text");

    System.out.println("Text: " + text);
}

For now this works perfectly fine, I get all the 4 "text" in the logs.

Now, my problem is that when I get response from server with only 1 or 2 data, something like this:

{
"notifications": {
    "0": {
        "id": "27429",
        "uID": "6967",
        "text": "Only one text here"
    }
}
}

Then my above logic fails, I get exception stating org.json.JSONException: No value for 1

How can I overcome this problem.

Any kind of help will be appreciated.


Solution

  • you can test if a key exists with rootObj.has("1") or use rootObj.optJSONObject("1");

    the former returns true if this object has a mapping for name. The latter returns the value mapped by name if it exists and is a JSONObject, null otherwise.

    Or you can interate through the keys inside rootObj, this way:

    Iterator<String> keys = jSearchData.keys();
    while (keys.hasNext()) {
          String key = keys.next();
          JSONObject jNotification0 = jSearchData.optJSONObject(key);
          if (jNotification0 != null) {
               String text = jNotification0.getString("text");
               String uID = jNotification0.getString("uID");
               String id = jNotification0.getString("id");
          }
    }