我想知道如何获得Json值?(从JSOn下面我想得到产品的“价格”以便我可以加入总数。非常感谢。
{ "StatusCode": 0
, "StatusInfo": "Processed and Logged OK"
, "PageNumber": 0
, "TotalPageCount": 1
, "TotalProductCount": 1
, "PageProductCount": 1
, "Products": [
{ "BaseProductId": "54158094"
, "EANBarcode": "3068320055008"
, "CheaperAlternativeProductId": ""
, "HealthierAlternativeProductId": ""
, "ImagePath": "http://img.tesco.com/Groceries/pi/008/3068320055008/IDShot_90x90.jpg"
, "MaximumPurchaseQuantity": 99
, "Name": "UNAVAILABLE: Evian Natural Mineral Water 500 Ml"
, "OfferPromotion": ""
, "OfferValidity": ""
, "OfferLabelImagePath": ""
, "Price": 0.51
, "PriceDescription": "(Unavailable)"
, "ProductId": "258247301"
, "ProductType": "QuantityOnlyProduct"
, "UnitPrice": 0.004
, "UnitType": "100ml" } ] }
答案 0 :(得分:0)
您可以使用JSONObject.getDouble()
方法或JSONObject.getInt()
方法。
JSONObject obj = new JSONObject("{ \"StatusCode\": 0, \"StatusInfo\": \"Pr...");
JSONArray products = obj.getJSONArray("Products");
JSONObject prod = products.getJSONObject(0);
double price = prod.getDouble("Price");
总结价格,只需循环遍历JSONArray
实例。
double sum = 0.0;
for(int i = 0; i < products.length(); i++) {
sum += products.getJSONObject(i).getDouble("Price");
}
...
答案 1 :(得分:0)
Price
标记值不是int
的双倍,因此如果您需要double
int
然后来自jsonobject的getInt
,但它会返回0
。由于0.5
值......
try {
String str="{ \"StatusCode\": 0....";
JSONObject objJsonObject = new JSONObject(str);
JSONArray array = objJsonObject.getJSONArray("Products");
Double d =array.getJSONObject(0).getDouble("Price");
System.out.print(d);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}