JSONObject parsing error when there is no value

和自甴很熟 提交于 2019-12-11 09:42:24

问题


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.


回答1:


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



回答2:


Edit: This is wrong, I read to fast and did not realize jSearchData was an object and not an array. But in my opinion if would make a lot more sense if it was in fact an array instead of an object.

There's no need to hard code the 4. Just take the length of the array and loop through it, like this:

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

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

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


来源:https://stackoverflow.com/questions/17489052/jsonobject-parsing-error-when-there-is-no-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!