我正在尝试从数组内部JSONArray
获取值,我能够成功地将整个 JSON 值检索到JSONArray
中,但无法检索JSONArray
中的值。当我将JSONArray
转换为JSONObject
以获取存储在JSONArray
中的值时.它给出错误:org.json.JSONException: No value for "banner"
我用 jsonlint.com 验证了 JSON 代码,它显示 JSON 是验证的,
[
{"code":"banner","moduletitle":0,
"banner":
[
{"image":"http://imageurl"},
{"image":"http://imageurl"},
{"image":"http://imageurl"}
]
}
]
我试图从 3 小时内得到这个,但没有运气。 我是 JSON 新手,不知道 JSON 实际工作原理,并且还阅读了旁边的 GSON 库以获取 JSON 值。 这是我的 Java 代码。
JSONArray jsonObj = null;
String image_url = "";
String banner_code ="";
try {
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs));
Log.d("value retrun :","" +jsonObj);
//---vlaue is coming and print in Log ----//
} catch (JSONException e) {
Log.v("Error in Parser :", " " + e);
Log.d("no value retrun :", "failed to convert");
}
try{
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
JSONArray subArray = jo.getJSONArray("banner");
image_url= subArray.getString(Integer.parseInt("image"));
Log.d("banner code",""+subArray);
}catch(Exception e)
{
Log.d("not working",""+e);
}
我把这个问题放在一起,但运气好:如何在 Android 中解析另一个 JSON 数组中的 JSON 数组
如果有人建议,我将不胜感激。 或者让我知道,在哪里可以获得有关 JSON 的更多信息
更新也感谢所有人,让他们有宝贵的时间来回答我愚蠢的问题。所有的答案都是正确的,但我只能接受一个答案。 非常感谢大家
在这里:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
因为解析jsonObj
JSONArray
所以不需要创建新的JSONArray
和JSONObject
从jsonObj
中提取它。 删除以上三行。
banner
JSONArray
在 jsonObj
JSONArray
包含的 JSONObject
内部,请将其获取为:
JSONObject jsonObject=jsonObj.optJSONObject(0);
JSONArray subArray = jsonObject.getJSONArray("banner");
// get code key from `jsonObject`
String strCode=jsonObject.optString("code");
// get all images urls from `subArray`
for(int index=0;index<subArray.length();index++){
JSONObject imgJSONObject=subArray.optJSONObject(index);
// get image urls
String strImgURL=imgJSONObject.optString("image");
}
此外,如果jsonObj
JSONArray 包含多个 JSONObject,则使用 for-loop
对其进行迭代。
我假设您拥有其余的可用值,因此仅发布此片段。
code=jsonObject.getString("code");
moduletitle=jsonObject.getString("moduletitle");
banner=jsonObject.getJSONArray("banner");
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs);
从上面的行,你会得到JSONArray。所以现在循环它并得到你的横幅JSONArray.再次循环横幅数组,你会得到图像网址
如果你想要 json arrray 中的"image"值,则比
String response = "your response";
try{
JsonArray jAry = new JsonArray(response);
JsonObject jObj = jAry.getJsonObject(0);
JsonArray jsonBanner = jObj.getJsonArray("banner");
JsonObject temp;
for(int i=0;i<jsonBanner.length;i++){
temp = jsonBanner.getJsonObject(i);
String image = temp.optString("image");
}
}