Hel*_*and 8 arrays android json
我必须将下面嵌套的Json数组的数据解析到我的应用程序中.我很困惑如何从中获取价值.
{
"prodCat_list": [
{
"prods": [
{
"cat_id": "9",
"position": "1",
"sku": "wwww345"
},
{
"cat_id": "9",
"position": "2",
"sku": "coof23"
},
{
"cat_id": "9",
"position": "3",
"sku": "dde45"
},
{
"cat_id": "9",
"position": "4",
"sku": "5555"
}
]
},
{
"prods": [
{
"cat_id": "9",
"position": "1",
"sku": "wwww345"
},
{
"cat_id": "9",
"position": "2",
"sku": "coof23"
},
{
"cat_id": "9",
"position": "3",
"sku": "dde45"
},
{
"cat_id": "9",
"position": "4",
"sku": "5555"
}
]
},
]
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以指导我如何获得内部价值.
我试过这个
JSONParser parser = new JSONParser();
JSONObject items = parser.getJSONFromUrl(productInfoUrl);
try {
JSONArray itemsDetails = items.getJSONArray("prodCat_list");
if(itemsDetails.length()>0){
for (int i = 0; i < itemsDetails.length(); i++) {
JSONArray productWithCategories = itemsDetails.getJSONArray(i);
JSONObject object = productWithCategories.getJSONObject(i);
Product productInfo = new Product( object.getString("sku"), object.getInt("cat_id"), object.getInt("position"));
ProductDbHandler productDbHandler = new ProductDbHandler(context);
productDbHandler.addProducts(productInfo);
}
}
else
System.out.println("No product to add");
} catch (JSONException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
har*_*ore 23
以下是我认为你的JSON Parser应该是这样的(可能有一些拼写错误,我没有在编辑器上测试这段代码:)):
JSONObject mainObj = new JSONOBject(myString);
if(mainObj != null){
JSONArray list = mainObj.getJSONArray("prodCat_list");
if(list != null){
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONArray prods = elem.getJSONArray("prods");
if(prods != null){
for(int j = 0; j < prods.length();j++){
JSONObject innerElem = prods.getJSONObject(j);
if(innerElem != null){
int cat_id = innerELem.getInt("cat_id");
int pos = innerElem.getInt("position");
String sku = innerElem.getString("sku");
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26577 次 |
| 最近记录: |