JSON String是这样的:
{
"products": [{
"Variants": [{
"SellPrice": "18.00",
"VariantID": "1",
"VariantName": "50 GM",
"InCart": "0",
"MRP": "19.00",
"VariantImagePath": null
}],
"SubCategoryID": "44",
"ProductImagePath": "/images/patanjali/1819.png",
"SubCategoryName": "Bathing Soap",
"BrandName": "Patanjali",
"ProductID": "1",
"BrandID": "112",
"ProductName": "Body Cleanser - Lemon Honey Kanti"
}, {
"Variants": [{
"SellPrice": "24.00",
"VariantID": "47",
"VariantName": "75 GM",
"InCart": "0",
"MRP": "25.00",
"VariantImagePath": null
}],
"SubCategoryID": "44",
"ProductImagePath": "/images/patanjali/1817.png",
"SubCategoryName": "Bathing Soap",
"BrandName": "Patanjali",
"ProductID": "2",
"BrandID": "112",
"ProductName": "Body Cleanser - Mogra"
}]
}
这个用于解析字符串的逻辑。
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("products");
//Iterate the jsonArray and print the info of JSONObjects
//utility.displayToast(jsonArray.length() + " ");
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("ProductID").toString());
String name = jsonObject.optString("ProductName").toString();
String imagePath = Utility.BASEURL + jsonObject.optString("ProductImagePath").toString();
int brandId = Integer.parseInt(jsonObject.optString("BrandID").toString());
String brandName = jsonObject.optString("BrandName").toString();
Brand b = new Brand(brandId, brandName, null);
JSONArray variantArray = jsonRootObject.optJSONArray("Variants");
ArrayList <ProductVariant> productVariant = new ArrayList<>();
for (int j = 0; j < variantArray.length(); ++j){
JSONObject variantObject = variantArray.getJSONObject(j);
int variantId = Integer.parseInt(variantObject.optString("VariantID").toString());
String variantName = variantObject.optString("VariantName");
Double variantMRP = Double.parseDouble(variantObject.optString("MRP").toString());
Double variantSellPrice = Double.parseDouble(variantObject.optString("SellPrice").toString());
Variant variant = new Variant(variantId, variantName);
ProductVariant pVariant = new ProductVariant(0, variantSellPrice, variantMRP, variant);
productVariant.add(pVariant);
}
Product p = new Product(id, name, imagePath, b, null, productVariant);
products.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
代码在此行中给出了NUllpointer异常错误
for(int j = 0; j&lt; variantArray.length(); ++ j){
有人可以帮我吗?