gpt4 book ai didi

java - 如何在 JSON 对象响应中访问 JSONArray 内部的 JSONArray

转载 作者:行者123 更新时间:2023-11-30 02:40:09 27 4
gpt4 key购买 nike

在此 Json 响应中,如何使用 Java 访问“smallImageUrls”并获取图像 url?

似乎“smallImageUrls”是“匹配”jsonarray 中的一个数组。如果我错了,请有人纠正我。

{  
"attribution":{
"html":"Recipe search powered by <a href='http://www.yummly.com/recipes'><img alt='Yummly' src='http://static.yummly.com/api-logo.png'/></a>",
"url":"http://www.yummly.com/recipes/",
"text":"Recipe search powered by Yummly",
"logo":"http://static.yummly.com/api-logo.png"
},
"totalMatchCount":17663,
"facetCounts":{

},
"matches":[
{
"imageUrlsBySize":{
"90":"http://lh3.ggpht.com/bTkxROvVTjHChEsGLRnkuwPoi-eNrHmESYP3xDHMsIisN-U06z-OfwErSjT5AHvMG0Ccgw8cN4mVqNyjWzbz=s90-c"
},
"sourceDisplayName":"Serious Eats",
"ingredients":[
"mayonnaise",
"crema mexican",
"feta",
"ancho powder",
"garlic",
"coriander leaf",
"shuck corn",
"lime"
],
"id":"Mexican-street-corn-_elotes_-370469",
"smallImageUrls":[
"http://lh5.ggpht.com/itong2VhnBU2mvPtzNimL58MnkC4l113RgNyrEWq8Jf76AsOGOlBoVQyCF-jYDPtzTB-7SoViNzyV5-Xe0NS=s90"
],
"recipeName":"Mexican Street Corn (Elotes)",
"totalTimeInSeconds":2400,
"attributes":{
"cuisine":[
"Mexican"
]
},
"flavors":{
"sweet":0.5,
"sour":0.6666666666666666,
"salty":0.6666666666666666,
"piquant":0.3333333333333333,
"meaty":0.3333333333333333,
"bitter":0.6666666666666666
},
"rating":5
}
],
"criteria":{
"excludedIngredients":null,
"allowedIngredients":null,
"terms":null
}
}

这是我目前拥有的代码。我可以访问所有其他字符串,但不能访问图像 url。

 JSONObject resObj = new JSONObject(result);
JSONArray foundrecipes = resObj.getJSONArray("matches");
for(int i = 0;i<foundrecipes.length(); i++){
JSONObject recipe = foundrecipes.getJSONObject(i);
String recipeName = recipe.getString("recipeName");
String rating = recipe.getString("rating");
String id = recipe.getString("id");
String imageurl = recipe.getString("smallImageUrls");

data.add(new Recipes(recipeName, rating, id, imageurl));
}

最佳答案

smallImageUrls,位于根内的匹配项内,因此您必须检索匹配项,并通过它检索 smallImageUrls

JSONObject obj = new JSONObject(...);
JSONArray matches = obj.optJSONArray("matches");
if (matches != null) {
for (int i = 0; i < matchesLenght; i++) {
JSONObject objAtIndex = matches.optJSONObject(i);
if (objAtIndex != null) {
JSONArray smallImageUrls = objAtIndex.optJSONArray("smallImageUrls");
for (int j = 0; j < smallImageUrlsSize; j++) {
String urlAtIndex = smallImageUrls.optString(j);
}
}
}

}

关于java - 如何在 JSON 对象响应中访问 JSONArray 内部的 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25894123/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com