[英]Error when getting data from JSON Nested loop in Android
我尝试了这个但是在for循环optJSONObject(i)中遇到错误
{
"response": {
"code": 1,
"message": "success"
},
"data": {
"updates": [
{
"id":"67",
"date":"6 months ago",
"update_type": "7",
"update_id": "67",
"name":"ravi"
},
{
"id":"68",
"date":"3 months ago",
"update_type": "5",
"update_id": "68",
"name":"paresh"
},
{
"id":"69",
"date":"1 months ago",
"update_type": "6",
"update_id": "69",
"name":"sampath"
},
{
"id":"62",
"date":"9 months ago",
"update_type": "6",
"update_id": "62",
"name":"raju"
}
]
}
}
我为此尝试的代码是:
try {
InputStream is = null;
is = getApplicationContext().getResources().openRawResource(R.raw.myfile);
//CONVERTS STREAM OBJ IN STRING OBJ
mJSONString = convertStreamToString(is);
JSONObject obj = new JSONObject(mJSONString);
JSONObject dataobj = obj.getJSONObject("data");
JSONObject updateobj = dataobj.getJSONObject("update");
//System.out.println(new JSONObject(update)toString(2));
for(int i=0; i<updateobj.length(); i++){
JSONObject object = updateobj.optJSONObject(i);
mUpdates = new Mobile_UpdateActivity();
mUpdates.update_id = object.getString("update_id");
mUpdates.site_id = object.getString("site_id");
mUpdates.update_type = object.getString("update_type");
System.out.println(mUpdates.update_id);
System.out.println(mUpdates.site_id);
System.out.println(mUpdates.update_type);
}
}
但我在** optJSONObject(i)时遇到错误
错误:JSONObject类型的方法optJSONObject(String)不适用于参数(int)**
您收到以下警告:
optJSONObject(i)错误:JSONObject类型的方法optJSONObject(String)不适用于参数(int)
因为在当前的JSON中,String updates
是一个JSONArray
而不是JSONObject
但是您正在尝试将JSONArray转换为JSONObject
您正在为JsonObject调用JsonObject.optJSONObject
,而JsonObject需要一个String作为参数,而不是JSONArray.optJSONObject
需要一个项目索引当前的JsonArray。 更改代码以避免当前警告:
//...your code here...
JSONObject obj = new JSONObject(mJSONString);
JSONObject dataobj = obj.getJSONObject("data");
// get update jsonArray from dataobj JSONObject
JSONArray updateobj = dataobj.getJSONArray("update");
//...your code here...
尝试替换行:
JSONObject updateobj = dataobj.getJSONObject("update");
至
JSONArray updateobj = dataobj.getJSONArray("update");
然后在for循环中:
JSONObject object = updateobj.optJSONObject(i);
至
JSONObject object = updateobj.get(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.