问题描述
我有一个 JSON
看起来像这样:
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"
}
}
}
我要带出文字
字符串从响应,这个我code是这样的:
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);
}
有关现在这个工作完全正常,我得到的所有4 文字
在日志
。
For now this works perfectly fine, I get all the 4 "text"
in the logs
.
现在,我的问题是,当我得到的只有1或2个数据服务器的响应,是这样的:
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"
}
}
}
然后我的上述逻辑失败,我得到异常说明 org.json.JSONException:1无值
我怎样才能解决这个问题。
How can I overcome this problem.
任何形式的帮助将是AP preciated。
Any kind of help will be appreciated.
推荐答案
您可以测试是否一个键与存在rootObj.has(1)
或使用 rootObj.optJSONObject(1);
you can test if a key exists with rootObj.has("1")
or use rootObj.optJSONObject("1");
前者返回true,如果该对象有名称的映射。如果它存在,并是后者返回由名称映射值的JSONObject
,否则返回null。
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.
或者你也可以通过内部rootObj键interate,这种方式:
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");
}
}
这篇关于JSONObject的解析错误时,有没有价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!