首先,我想檢索嵌套在評級名稱中的所有費率值,並假設我不知道在那裏有多少評級,所以應該有某種類型的循環檢查它們。 json對象如下所示。ANDROID JSON從嵌套鍵檢索多個值
{
"restaurant": [
{
"restaurantId": "1",
"restaurantName": "Restaurant A",
"area": "Skudai",
"state": "Johor",
"rating": [
{
"ratingId": "1",
"rate": "5",
"comment": null,
"userId": "15"
},
{
"ratingId": "2",
"rate": "4",
"comment": null,
"userId": "14"
}
]
},
{
"restaurantId": "2",
"restaurantName": "Restaurant 2",
"area": "Skudai",
"state": "Johor",
"rating": null
}
],
"success": 1
}
下面是在while循環的retrieveng部分看起來不太正確的代碼。對於getAverage中的JSONObject參數,我已經拿到了第一家只有餐廳A的餐廳,餐廳2不包括在內。
public int getAverage(JSONObject jsonObject){
int average = 0, count = 0;
while (jsonObject.has("rate")){
average += Integer.parseInt(jsonObject.optString("rate"));
count++;
}
average /= count;
return average;
}
如何使用optString()來計算平均從嵌套等級的檢索頻率的倍數值,或者我應該用其他的方式來找回?
你的代碼在哪裏?你嘗試過什麼? –
複製json響應,粘貼到http://json2csharp.com,它給你類作爲C#,將類轉換爲Java,使用GSON解析JSON。如果你不能,請檢查這個http://stackoverflow.com/questions/36625488/how-to-deserialize-json-with-a-string-url-name-value-pair/36625899#36625899 –