我试图从嵌套的JSON数组中获取值但是获得Null。 这是我的java代码:
JSONObject root = new JSONObject(items);
JSONArray arr = root.getJSONArray("product");
for (int i = 0; i < arr.length(); i++)
{
JSONObject obj = (JSONObject) arr.get(i);
path = "" + obj.optString("image");
al_prod_id.add("" + obj.optString("product_id"));
al_prod_name.add("" + obj.optString("product_name"));
al_prod_price.add(""+ obj.optString("price"));
al_prod_image.add(""+imagebase+path);
}
setupProductforMall();
这是我的JSON:
{
"status": "success",
"data": {
"flashsale_id": "1",
"flashsale_name": "New Summer Sale",
"flashsale_image": "aa.jpg",
"flashsale_product": "8,11,12",
"discount": "20",
"st_time": "10/05/2017 10:25:59",
"ed_time": "30/05/2017 10:25:59",
"product": [
{
"0": {
"product_id": "8",
"product_name": "Prottin Shake",
"price": "799/-",
"stock": "100",
"description": "This is
strongest drink that gives
you instant energy",
"image":
"ea0fb7c33d9c025627fbb2f591e09083.png",
"Discount": "30%",
"Discount_on": "1",
"Coupan_Code": "ADFG235"
}
},
{
"0": {
"product_id": "11",
"product_name": "GYM Product",
"price": "7500",
"stock": "15",
"description": "Best Product",
"image":
"be804ee59ccb0597f8ac2cd6e186954c.png",
"Discount": "40%",
"Discount_on": "2",
"Coupan_Code": "BVC9988"
}
}
]
},
"message": "flashsale "
}
如何获取嵌套的JSON?如何在android中获取二维数组?我试过嵌套for循环但仍然得到空数组?请帮我解决,我是android新手。
答案 0 :(得分:4)
您需要getJSONObject
来获取JSONObject
,而不是通过投放它。
更改此行:
JSONObject obj = (JSONObject) arr.get(i);
到此:
JSONObject obj = arr.getJSONObject(i);
答案 1 :(得分:1)
您在产品 JSONArray 的JSONObjects中缺少 JSONObject“0”。你应该像这样解析你的JSON -
try{
JSONObject root = new JSONObject(items);
JSONObject data = root.getJSONObject("data");
JSONArray productArray = data.getJSONArray("product");
for (int i=0; i<productArray.length();i++){
JSONObject productObjects = productArray.getJSONObject(i);
JSONObject productIndex = productObjects.getJSONObject("0");
path = "" + productIndex.getString("image");
al_prod_id.add("" + productIndex.getString("product_id"));
al_prod_name.add("" + productIndex.getString("product_name"));
al_prod_price.add(""+ productIndex.getString("price"));
al_prod_image.add(""+imagebase+path);
}
}
catch (JSONException ex){
ex.getMessage();
}
希望它会有所帮助.. :)
答案 2 :(得分:0)
解析json的最好方法是借助json to pojo website
创建一个pojo类。如果json中有嵌套,则只需对所有pojo类实现Parcelable Interface。
答案 3 :(得分:0)
使用此:
public static Object getValue(JSONObject jsonObject, String key)
{
if (jsonObject.has(key))
{
return jsonObject.get(key);
}
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext())
{
Object value = jsonObject.get(iterator.next());
if (value instanceof JSONObject)
{
return getValue((JSONObject) value, key);
}
else if (value instanceof JSONArray)
{
for (int i = 0; i < ((JSONArray) value).length(); i++)
{
return getValue(((JSONArray) value).getJSONObject(i), key);
}
}
}
return "not found";
}