我似乎遇到了循环JSONObject
的问题以下循环位于try catch中。我试图循环返回JSON,但它跳过
try {
JSONObject jsonObject = new JSONObject(result);
// Extract data from json and store into ArrayList as class objects
for(int i = 0; i < jsonObject.length(); i++){
JSONObject jD = jsonObject.getJSONObject(i).;
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}
响应JSON
{"count": 30, "recipes": [{"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"}, {"publisher": "The Pioneer Woman",
onPostExecute中的代码。 即使这些改变仍然忽略了内部并直接进入捕获。
@Override
protected void onPostExecute(String result) {
List<DataRecipes> data = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArrayRecipe = jsonObject.getJSONArray("recipes");
for(int i = 0; i < jsonArrayRecipe.length(); i++){
JSONObject jD = jsonArrayRecipe.getJSONObject(i);
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}
// Setup and Handover data to recyclerview
mRVRecipePrice = findViewById(R.id.jsonText);
mAdapter = new AdapterRecipe(Main_Food.this, data);
mRVRecipePrice.setAdapter(mAdapter);
mRVRecipePrice.setLayoutManager(new LinearLayoutManager(Main_Food.this));
}
答案 0 :(得分:1)
您需要先访问配方数组
试试这个
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArrayrecipe = jsonObject .getJSONArray("recipes");
for(int i = 0; i < jsonArrayrecipe .length(); i++){
JSONObject jD = jsonArrayrecipe .getJSONObject(i);
DataRecipes recipeData = new DataRecipes();
recipeData.image_url = jD.getString("image_url");
recipeData.title = jD.getString("title");
recipeData.publisher = jD.getString("publisher");
data.add(recipeData);
}
} catch (JSONException e) {
Toast.makeText(Main_Food.this, e.toString(), Toast.LENGTH_LONG).show();
}