如何使用 Volley 将此 json 数组提取到数组中?

How do I extract this json Array inside of an Array with Volley?

json Image我正在尝试从 Json 对象中提取数据列表(数组),但我不知道。这是我要提取的 "ingredients" 的值。我试图将其提取为字符串,但结果未格式化。我还提供了原始图像 jsonenter code here。如果我尝试将其提取为 'cake.optJSONArray' 我会得到 java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.List 我添加了更多代码来帮助问题变得有意义(祈祷我没有让它变得更混乱)。

   try {

                for (int i = 0; i < response.length(); i++) {
                    JSONObject cake = response.getJSONObject(i);

                    String cakeId = cake.optString("id");
                    String cakeName = cake.optString("name");


                    List<Ingredients> ingredients = (List<Ingredients>) cake.optJSONArray("ingredients");

                    mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
                }

public class CakesItem {

private String mId;
private List<Ingredients> mIngredients;
private String mName;

public CakesItem(String cakeId, Lists <Ingrediets> ingredients String cakeName) {
    mId = cakeId;
    mIngredients = ingredients;
    mName = cakeName;

}

public class Ingredients 实现 Parcelable {

private double quantity;
private String measure, ingredient;


public Ingredients() {
}

我不确定你使用的是什么 JSON 库,但是如果你导入 org.json.JSONArray,那么如果你的蛋糕是 org.json.JSONObject 你从 JSON从 Volley 返回的对象响应,您可以使用以下语法:

JSONObject cake = response.getJSONObject(i);
JSONArray ingredients = cake.getJSONArray("ingredients");

然后,您可以将 JSONArray 成分中的值放入您的列表中。它看起来像这样:

for (int i = 0; i < response.length(); i++) {
    JSONObject cake = response.getJSONObject(i);

    String cakeId = cake.optString("id");
    String cakeName = cake.optString("name");

    JSONArray JSONingredients = cake.optJSONArray("ingredients");

    List<Ingredients> ingredients = new List<Ingredients>();

    for (int j = 0; j < JSONingredients.length(); j++) {
        JSONObject item = JSONingredients.getObject(j);

        String measure = item.getString(“measure”);
        String ingredient = item.getString(“ingredient”);
        Double quantity = item.getDouble(“quantity”);

        Ingredients item2 = new Ingredients(measure, ingredient, quantity);
        ingredients.add(item2);
      } 


      mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
    }