我正在使用Yummly API中的数据来获取食谱详细信息。我正在创建一个Android应用程序,它将根据用户输入的匹配成分显示食谱。我试图进入“recipeName”标签,但它抱怨它没有价值,我尝试了各种方法。我正在尝试将所有配方名称添加到HashMap中,稍后将在ListView中显示。
下面是JSON对象形式的一个配方(39个)的示例。
{
"attribution": {
"html": "<a href='http://www.yummly.com/recipes/soup'>soup recipes</a> search powered by <img src=''/>",
"url": "http://www.yummly.com/recipes/soup",
"text": "soup recipes: search powered by Yummly",
"logo": ""
},
"totalMatchCount": 39,
"facetCounts": {},
"matches": [
{
"attributes": {
"course": [
"Soups"
],
"cuisine": [
"Italian"
]
},
"flavors": {
"salty": 0.6666666666666666,
"sour": 0.8333333333333334,
"sweet": 0.6666666666666666,
"bitter": 0.5,
"meaty": 0.16666666666666666,
"piquant": 0.5
},
"rating": 4.6,
"id": "Vegetarian-Cabbage-Soup-Recipezaar",
"smallImageUrls": [],
"sourceDisplayName": "Food.com",
"totalTimeInSeconds": 4500,
"ingredients": [
"garlic cloves",
"ground pepper",
"diced tomatoes",
"celery",
"tomato juice",
"salt",
"cabbage",
"bell peppers",
"oregano",
"carrots",
"basil",
"vegetable broth",
"chili pepper flakes",
"green beans",
"onions",
"onion soup mix"
],
"recipeName": "Vegetarian Cabbage Soup"
}
}
我的搜索类的片段
//imports above
private static final String TAG_TOTAL_MATCH = "totalMatchCount";
private static final String TAG_MATCHES = "matches";
private static final String TAG_NAME = "recipeName";
private static final String TAG_RATING = "rating";
JSONParser jsonParser = new JSONParser();
protected String doInBackground(String... args) {
JSONObject json = jsonParser.makeHttpRequest(full_url, "GET", params);
// check log cat for JSON response
Log.d("Response", json.toString());
// check for success tag
try {
int count = json.getInt(TAG_TOTAL_MATCH);
String name = json.getString(TAG_NAME);
String matches = json.getString(TAG_MATCHES);
JSONObject namelist = json.getJSONObject(matches).getJSONObject(name);
HashMap<String, String> pairs = new HashMap<String, String>();
if (count > 0) {
int i;
//populate Hashmap with recipe names
for (i=1; i<=count; i++){
Iterator it = namelist.keys();
while (it.hasNext()) {
String n = (String) it.next();
pairs.put(n,name);
}
}
//display Hashmap in terminal
for(int j =0; j<pairs.size(); j++) {
System.out.println(pairs.get(j));
}
}
}
}
我没有包含所有内容,因为它不相关。 Log.d()确实给了我一个JSON对象,就像这个问题顶部显示的那样,所以JSON被成功解析,只是Android工作室说没有“recipeName”的值。我做错了什么?
答案 0 :(得分:1)
recipeName
和rating
位于matches
内,但您尝试访问它们,就像它们与totalMatchCount
处于同一级别一样。
首先,请考虑删除此行:
String matches = json.getString(TAG_MATCHES);
并更改下一行以从根对象中获取matches数组:
JSONArray matches = json.getJSONArray(TAG_MATCHES);
我确定你可以通过迭代匹配数组并独立处理每个食谱来从中获取它。