在这个Json响应中,如何访问“smallImageUrls”并使用Java获取图像URL?
似乎“smallImageUrls”是“matches”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
}
}
这是我目前拥有的代码。我可以访问所有其他字符串,而不是图像网址。
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));
}
答案 0 :(得分:1)
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);
}
}
}
}