JSON解析Bug排查:Ingredients对象重复添加问题求助
问题排查与修复方案
嘿,我马上就发现问题所在了——你在复用同一个列表实例,导致所有Recipe对象的Ingredients都指向最后一次循环填充的内容!
问题根源
你在convert方法开头初始化了ingredients和steps这两个列表:
List<Steps> steps = new ArrayList<>(); List<Ingredients> ingredients = new ArrayList<>();
然后在遍历每个食谱的循环里,你只是调用ingredients.clear()和steps.clear(),接着往这两个列表里加当前食谱的配料和步骤,最后把它们传给Recipe构造函数。
但这里的坑是:所有的Recipe对象引用的都是同一个ingredients和steps列表。当你处理下一个食谱时,clear()会清空这个列表,再添加新内容——这会直接修改之前已经加入recipesList的所有Recipe对象的配料/步骤,最后所有食谱自然都显示最后那一组配料了。
修复方法
把ingredients和steps的初始化移到外层循环内部,也就是每处理一个新食谱,就新建一个列表实例:
修改后的核心代码:
public static List<Recipe> convert (String json) { List<Recipe> recipesList = new ArrayList<>(); // 删掉这里的ingredients和steps初始化 try { JSONArray baseJsonArray = new JSONArray(json); for (int i = 0; i < baseJsonArray.length(); i++) { // 每个食谱都用全新的列表,互不干扰 List<Ingredients> ingredients = new ArrayList<>(); List<Steps> steps = new ArrayList<>(); JSONObject recipeObject = baseJsonArray.getJSONObject(i); int recipeId = recipeObject.getInt(RECIPE_ID); String name = recipeObject.getString(RECIPE_NAME); int servings = recipeObject.getInt(SERVINGS); String image = recipeObject.getString(IMAGE); // 配料解析逻辑不变 JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS); for (int j = 0; j < ingredientsArray.length(); j++) { JSONObject ingredientObject = ingredientsArray.getJSONObject(j); float quantity = ingredientObject.getInt(QUANTITY); String measure = ingredientObject.getString(MEASURE); String ingredient = ingredientObject.getString(INGREDIENT); ingredients.add(new Ingredients(quantity, measure, ingredient)); } // 步骤解析逻辑不变 JSONArray stepArray = recipeObject.getJSONArray(STEP); for (int k = 0; k < stepArray.length(); k++) { JSONObject stepsObject = stepArray.getJSONObject(k); int stepId = stepsObject.getInt(STEP_ID); String shortDescription = stepsObject.getString(SHORT_DESCRIPTION); String description = stepsObject.getString(DESCRIPTION); String videoURL = stepsObject.getString(VIDEO_URL); String thumbnailURL = stepsObject.getString(THUMBNAIL); steps.add(new Steps(stepId, shortDescription, description, videoURL, thumbnailURL)); } recipesList.add(new Recipe(recipeId, name, servings, image, ingredients, steps)); } } catch (JSONException e) { e.printStackTrace(); } return recipesList; }
额外小提示
你定义的quantity是float类型,但JSON里的quantity是整数,用getInt()赋值没问题,但如果后续有小数形式的配料数量,记得改成getDouble()再转成float,避免潜在的类型转换问题。
内容的提问来源于stack exchange,提问作者Dia
相关产品推荐
相关产品推荐

