【发布时间】:2015-12-10 08:53:37
【问题描述】:
我在从 API Get 调用的 JSONArray 构建 ArrayList 时遇到了一些问题。我收到一个空列表。我在通话中做错了什么?
我尝试接收的JSONArray 是“recipes”。我只需要“title”和“image_url”。
{"count": 2, "recipes": [{"publisher": "The Pioneer Woman", "f2f_url": "http://food2fork.com/view/47024", "title": "Perfect Iced Coffee", "source_url": "http://thepioneerwoman.com/cooking/2011/06/perfect-iced-coffee/", "recipe_id": "47024", "image_url": "http://static.food2fork.com/icedcoffee5766.jpg", "social_rank": 100.0, "publisher_url": "http://thepioneerwoman.com"}, {"publisher": "Closet Cooking", "f2f_url": "http://food2fork.com/view/35382", "title": "Jalapeno Popper Grilled Cheese Sandwich", "source_url": "http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html", "recipe_id": "35382", "image_url": "http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg", "social_rank": 100.0, "publisher_url": "http://closetcooking.com"}]}
我用来检索 JSONArray 并将其存储到 ArrayList 中的方法。
public class JsonHelper {
public List<Recipe> getRecipes(String jsonText) {
List<Recipe> list = new ArrayList<Recipe>();
try {
JSONObject jsonObject = new JSONObject(jsonText);
JSONArray jsonArrayRecipes = jsonObject.getJSONArray("recipes");
for (int i = 0; i < jsonArrayRecipes.length(); i++) {
JSONObject jsonObjectRecipe = jsonArrayRecipes.getJSONObject(i);
Recipe recipe = new Recipe();
recipe.setImage_url(jsonObjectRecipe.getString("title"));
recipe.setName(jsonObjectRecipe.getString("image_url"));
list.add(recipe);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return list;
}}
活动类中使用的方法。我在 API 调用中模糊了 devkey(链接有效,见结果:上图)。
private void readRecipes()
{
HttpReader httpReader = new HttpReader();
httpReader.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
@Override
public void resultReady(String result) {
JsonHelper jsonHelper = new JsonHelper();
recipes = jsonHelper.getRecipes(result);
}
});
httpReader.execute("http://food2fork.com/api/search?key={devkey}&q=");
}
任何帮助将不胜感激。提前致谢!
【问题讨论】:
-
这段代码的结果是什么?
-
你只想要什么值转换成数组列表
-
真正的问题是什么?
-
发布实际错误
-
对不起,我是网站上的新人。我发布了一些我用来进行 API 调用的方法的额外代码。问题是我收到一个空的 ArrayList。我想我在 JSONHelper 中尝试做错事。
标签: java android json arraylist