分析多维JSON数组错误



Hi All我正在尝试解析一个包含多维数组的JSON字符串。我在日志中不断收到以下错误->W/System.err:org.json.JSONException:没有营养素值,此错误对应于以下行->JSONArray jsonArray1=jsonObject.getJSONArray("营养素"(;

有人能帮我解决这个问题吗。提前感谢

我试图解析的JSON字符串->

{
"results": [
{
"id": 654959,
"title": "Pasta With Tuna",
"image": "https://spoonacular.com/recipeImages/654959-312x231.jpg",
"imageType": "jpg",
"nutrition": {
"nutrients": [
{
"title": "Calories",
"amount": 420.823,
"unit": "kcal"
},
{
"title": "Protein",
"amount": 24.4751,
"unit": "g"
},
{
"title": "Fat",
"amount": 10.3277,
"unit": "g"
},
{
"title": "Carbohydrates",
"amount": 57.6915,
"unit": "g"
}
]
}
}

我的Java代码来解析它->

try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
int id = jsonArray.getJSONObject(i).getInt("id");
String title = jsonArray.getJSONObject(i).getString("title");
String image = jsonArray.getJSONObject(i).getString("image");
Log.i("a", "" + title);
JSONArray jsonArray1 = jsonObject.getJSONArray("nutrients");
for(int e = 0; e < jsonArray1.length(); e++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(e);
double calories = jsonObject1.getDouble("amount");
Log.i("calories", "" + calories);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

您的JSON无效。

这是一个有效的

{
"results": [
{
"id": 654959,
"title": "Pasta With Tuna",
"image": "https://spoonacular.com/recipeImages/654959-312x231.jpg",
"imageType": "jpg",
"nutrition": {
"nutrients": [
{
"title": "Calories",
"amount": 420.823,
"unit": "kcal"
},
{
"title": "Protein",
"amount": 24.4751,
"unit": "g"
},
{
"title": "Fat",
"amount": 10.3277,
"unit": "g"
},
{
"title": "Carbohydrates",
"amount": 57.6915,
"unit": "g"
}
]
}
}
]
}

然后你的Java代码

try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject resultsObject=jsonArray.getJSONObject(0);
int id = resultsObject.getInt("id");
String title = resultsObject.getString("title");
String image =resultsObject.getString("image");
Log.i("a", "" + title);
JSONObject nutrition = resultsObject.getJSONObject("nutrition");
JSONArray nutrients = nutrition.getJSONArray("nutrients");
for(int e = 0; e < nutrients.length(); e++) {
JSONObject jsonObject1 = nutrients.getJSONObject(e);
double calories = jsonObject1.getDouble("amount");
Log.i("calories", "" + calories);
}
} catch (JSONException e) {
e.printStackTrace();
}

希望有帮助!

相关内容

  • 没有找到相关文章

最新更新