gpt4 book ai didi

java - JSON 上的 for 循环出现问题

转载 作者:行者123 更新时间:2023-12-02 11:50:24 25 4
gpt4 key购买 nike

我似乎在循环 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));
}

最佳答案

您需要先访问配方数组

试试这个

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();
}

关于java - JSON 上的 for 循环出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916347/

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