我试图解析以下json
{
"status": 1,
"value": {
"star1": {
"0": "Response from Vaighai is good",
"1": "Shipment process is fine"
},
"star2": {
"0": "Shipment process is fine",
"1": "Response from Vaighai is good",
"2": "Shipment status through app is"
}
}
}
这是我使用的代码
JSONObject value = new JSONObject(notificationResponse.getString("value"));
JSONObject starOne = value.getJSONObject("star1");
JSONObject starTwo = value.getJSONObject("star2");
Iterator<String> starOneIterator = starOne.keys();
Iterator<String> starTwoIterator = starTwo.keys();
String starOnestatus = null;
String starOnekey = null;
String starTwostatus = null;
String starTwokey = null;
while (starOneIterator.hasNext()){
starOnekey = starOneIterator.next();
starOnestatus = starOne.optString(starOneIterator.next());
}
while (starTwoIterator.hasNext()){
starTwokey = starTwoIterator.next();
starTwostatus = starTwo.optString(starTwoIterator.next());
}
我收到以下错误消息,
java.util.NoSuchElementException
..我可能在运行时不知道密钥,所以我在while循环中迭代它,但错误消息被解雇了。
答案 0 :(得分:3)
更改
starOnestatus = starOne.optString(starOneIterator.next());
到
starOnestatus = starOne.optString(starOnekey);
此更改也适用于其他迭代。
答案 1 :(得分:1)
将此更改为
JSONObject jObjRoot = new JSONObject(notificationResponse.toString());
JSONObject jObjvalue = jObjRoot.getJSONObject("value");
JSONObject starOne = jObjvalue.getJSONObject("star1");
JSONObject starTwo = jObjvalue.getJSONObject("star2");
Iterator<String> starOneIterator = starOne.keys();
Iterator<String> starTwoIterator = starTwo.keys();
String starOnestatus = null;
String starOnekey = null;
String starTwostatus = null;
String starTwokey = null;
while (starOneIterator.hasNext()){
starOnekey = starOneIterator.next();
starOnestatus = starOne.optString(starOneIterator.next());
}
while (starTwoIterator.hasNext()){
starTwokey = starTwoIterator.next();
starTwostatus = starTwo.optString(starTwoIterator.next());
}