我需要根据下面使用Java的JSON响应中的“full_nutrients”数组中的“attr_id”获取相应的“值”,如何实现?例如,我想在“attr_id”== 205时获取值。
JSON响应:
"foods": [
{
"food_name": "chicken noodle soup",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "cup",
"serving_weight_grams": 248,
"nf_calories": 62,
"nf_total_fat": 2.36,
"nf_saturated_fat": 0.65,
"nf_cholesterol": 12.4,
"nf_sodium": 865.52,
"nf_total_carbohydrate": 7.32,
"nf_dietary_fiber": 0.5,
"nf_sugars": 0.67,
"nf_protein": 3.15,
"nf_potassium": 54.56,
"nf_p": 42.16,
"full_nutrients": [
{
"attr_id": 203,
"value": 3.1496
},
{
"attr_id": 204,
"value": 2.356
},
{
"attr_id": 205,
"value": 7.316
},
{
"attr_id": 207,
"value": 2.5048
}],
}
答案 0 :(得分:3)
您的json
无效。
您可以更改为此。
{"foods": [
{
"food_name": "chicken noodle soup",
"brand_name": null,
"serving_qty": 1,
"serving_unit": "cup",
"serving_weight_grams": 248,
"nf_calories": 62,
"nf_total_fat": 2.36,
"nf_saturated_fat": 0.65,
"nf_cholesterol": 12.4,
"nf_sodium": 865.52,
"nf_total_carbohydrate": 7.32,
"nf_dietary_fiber": 0.5,
"nf_sugars": 0.67,
"nf_protein": 3.15,
"nf_potassium": 54.56,
"nf_p": 42.16,
"full_nutrients": [
{
"attr_id": 203,
"value": 3.1496
},
{
"attr_id": 204,
"value": 2.356
},
{
"attr_id": 205,
"value": 7.316
},
{
"attr_id": 207,
"value": 2.5048
}],
}
}
试试这个
try {
// if your response is { },you can use JSONObject
JSONObject jsonObject = new JSONObject(response);
// then find the foods tag in your json data
JSONArray foods = jsonObject.getJSONArray("foods");
// loop for the JSONArray
for (int i = 0; i < foods.length(); i++) {
// getJSONObject from the index
JSONObject jsonObject1 = foods.getJSONObject(i);
// then get full_nutrients tag
JSONArray full_nutrients = jsonObject1.getJSONArray("full_nutrients");
// loop for the JSONArray
for (int j = 0; j < full_nutrients.length(); j++) {
// getJSONObject from the index again
JSONObject jsonObject2 = full_nutrients.getJSONObject(i);
// get attr_id
String attr_id = jsonObject2.getString("attr_id");
// get value
String value = jsonObject2.getString("value");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:2)
试试这个:
function Double GetValue(String json_object, int attr_id) {
Double tResult = 0;
JSONObject reader = new JSONObject(json_object);
// Getting JSON Array node
JSONArray full_nutrients = reader.getJSONArray("full_nutrients");
// looping through All full_nutrients
for (int i = 0; i < full_nutrients.length(); i++) {
JSONObject c = full_nutrients.getJSONObject(i);
if (c.getInt("attr_id") == attr_id)
tResult = c.getDouble("value");
}
return tResult;
}