java - 如何在 JSONArray 中正确嵌套数组

标签 java android arrays

我是 Android 的新手,正在为如何处理从 API 检索到的数据而苦苦挣扎 here .这是一个食谱。下面是一个例子。我正在努力的是创建一个包含所有项目的 jsonArray ,我可以使用它来在详细 View 中显示食谱及其成分和步骤。我可以获得 ID 和名称,单个项目很好,特别是较大配方数组中的成分和步骤数组是我不太正确的。

[{"id":2,
 "name":"Brownies",
 "ingredients":[{"quantity":350,"measure":"G","ingredient":"Bittersweet chocolate (60-70% cacao)"},
     {"quantity":226,"measure":"G","ingredient":"unsalted butter"},
     {"quantity":300,"measure":"G","ingredient":"granulated sugar"},
     {"quantity":100,"measure":"G","ingredient":"light brown sugar"},
     {"quantity":5,"measure":"UNIT","ingredient":"large eggs"},
     {"quantity":1,"measure":"TBLSP","ingredient":"vanilla extract"},
     {"quantity":140,"measure":"G","ingredient":"all purpose flour"},
     {"quantity":40,"measure":"G","ingredient":"cocoa powder"},
     {"quantity":1.5,"measure":"TSP","ingredient":"salt"},
     {"quantity":350,"measure":"G","ingredient":"semisweet chocolate chips"}],
 "steps":[{"id":0,"shortDescription":"Recipe Introduction","description":"Recipe Introduction","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdc33_-intro-brownies\/-intro-brownies.mp4","thumbnailURL":""},
     {"id":1,"shortDescription":"Starting prep","description":"1. Preheat the oven to 350�F. Butter the bottom and sides of a 9\"x13\" pan.","videoURL":"","thumbnailURL":""},
     {"id":2,"shortDescription":"Melt butter and bittersweet chocolate.","description":"2. Melt the butter and bittersweet chocolate together in a microwave or a double boiler. If microwaving, heat for 30 seconds at a time, removing bowl and stirring ingredients in between.","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdc43_1-melt-choclate-chips-and-butter-brownies\/1-melt-choclate-chips-and-butter-brownies.mp4","thumbnailURL":""},
     {"id":3,"shortDescription":"Add sugars to wet mixture.","description":"3. Mix both sugars into the melted chocolate in a large mixing bowl until mixture is smooth and uniform.","videoURL":"","thumbnailURL":""},
     {"id":4,"shortDescription":"Mix together dry ingredients.","description":"4. Sift together the flour, cocoa, and salt in a small bowl and whisk until mixture is uniform and no clumps remain. ","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdc9e_4-sift-flower-add-coco-powder-salt-brownies\/4-sift-flower-add-coco-powder-salt-brownies.mp4","thumbnailURL":""},{"id":5,"shortDescription":"Add eggs.","description":"5. Crack 3 eggs into the chocolate mixture and carefully fold them in. Crack the other 2 eggs in and carefully fold them in. Fold in the vanilla.","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdc62_2-mix-egss-with-choclate-butter-brownies\/2-mix-egss-with-choclate-butter-brownies.mp4","thumbnailURL":""},{"id":6,"shortDescription":"Add dry mixture to wet mixture.","description":"6. Dump half of flour mixture into chocolate mixture and carefully fold in, just until no streaks remain. Repeat with the rest of the flour mixture. Fold in the chocolate chips.","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdcc8_5-mix-wet-and-cry-batter-together-brownies\/5-mix-wet-and-cry-batter-together-brownies.mp4","thumbnailURL":""},{"id":7,"shortDescription":"Add batter to pan.","description":"7. Pour the batter into the prepared pan and bake for 30 minutes.","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdcf4_8-put-brownies-in-oven-to-bake-brownies\/8-put-brownies-in-oven-to-bake-brownies.mp4","thumbnailURL":""},{"id":8,"shortDescription":"Remove pan from oven.","description":"8. Remove the pan from the oven and let cool until room temperature. If you want to speed this up, you can feel free to put the pan in a freezer for a bit.","videoURL":"","thumbnailURL":""},{"id":9,"shortDescription":"Cut and serve.","description":"9. Cut and serve.","videoURL":"https:\/\/d17h27t6h515a5.cloudfront.net\/topher\/2017\/April\/58ffdcf9_9-final-product-brownies\/9-final-product-brownies.mp4","thumbnailURL":""}],
"servings":8,
"image":""}]

我一直试图用来处理这些数据的是这个。

public static String[] getSimpleRecipeStringsFromJson(Context context, String recipeJsonStr)
        throws JSONException {

    String[] parsedRecipeData = null;

    JSONArray recipeJSONArray = new JSONArray(recipeJsonStr);

    parsedRecipeData = new String[recipeJSONArray.length()];

    // Loop through the recipe array
    for (int i = 0; i < recipeJSONArray.length(); i++) {
        JSONObject recipeDetails = recipeJSONArray.getJSONObject(i);
        String recipeID    = recipeDetails.getString("id");
        String recipeName  = recipeDetails.getString("name");
        String recipeIngredients  = recipeDetails.getString("ingredients");
        String servings    = recipeDetails.getString("servings");
        String image       = recipeDetails.getString("image");

        String[] parsedRecipeIngredientsData = null;
        JSONArray recipeIngredientsJSONArray = new JSONArray(recipeIngredients);
        parsedRecipeIngredientsData = new String[recipeIngredientsJSONArray.length()];

        // Loop through ingredients array
        for (int ingredient = 0; ingredient < recipeIngredientsJSONArray.length(); ingredient++) {
            JSONObject ingredientDetails = recipeIngredientsJSONArray.getJSONObject(ingredient);
            String ingredientQuantity = ingredientDetails.getString("quantity");
            String ingredientMeasure = ingredientDetails.getString("measure");
            String ingredientIngredient = ingredientDetails.getString("ingredient");
            parsedRecipeIngredientsData[ingredient] = "\"" + ingredientQuantity + "\",\"" + ingredientMeasure + "\",\"" + ingredientIngredient + "\"";
            Log.d(TAG, "CHECK : " + parsedRecipeIngredientsData[ingredient]);
        }

        parsedRecipeData[i] = "[\"" + recipeID + "\",\"" + recipeName +  "\",\"" + parsedRecipeIngredientsData + "]\",\""  + servings + "\",\"" + image + "\"]";
        Log.d(TAG, "TAG : " + parsedRecipeData[i]);
    }
    return parsedRecipeData;
}

我在这样的详细 View 中使用它,现在它只显示配方名称,这是我需要所有信息的地方。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recipe_detail);

    // Creating variables for each of the items we need to display
    mRecipeName = (TextView) findViewById(R.id.recipe_name);
    mRecipeIngredients = (TextView) findViewById(R.id.recipe_ingredients);

    Intent intentThatStartedThisActivity = getIntent();

    if (intentThatStartedThisActivity != null) {

        if (intentThatStartedThisActivity.hasExtra(Intent.EXTRA_TEXT)) {
            Context context = getApplicationContext();
            mRecipe = intentThatStartedThisActivity.getStringExtra(Intent.EXTRA_TEXT);
            try {
                JSONArray jsonArray = new JSONArray(mRecipe);
                String recipeID = jsonArray.getString(0);
                // Display title
                mRecipeName.setText(jsonArray.getString(1));
            } catch (JSONException e) {
                Log.d(TAG, "CHECK : " + e);
                e.printStackTrace();
            }
        }
    }
}

我希望我可以创建稍后可以循环的成分和步骤数组,但我不断收到错误。此代码生成的对象如下所示。

["4","Cheesecake","[Ljava.lang.String;@e5c064e}","8",""]

所以 java.lang.string 是问题所在。我虽然创建一个 String[] 可以让我稍后循环它,因为这是发送到这个方法的数据,我只是想复制它,但我无法让它工作。我得到错误

 unterminated array character at ### (the numbers  change)

所以也许我只是格式设置不正确,或者我需要一种不同的方法。如果有人可以提示我如何将上面的食谱之类的东西处理成可用的 jsonArray,我可以用它来填充 View ,我将不胜感激。即使只是指向要研究的示例或方法的链接,我们也会非常感激。

最佳答案

您可以使用gson 更轻松地解析JSON 数据。 在您的 build.gradle 文件中添加此依赖项。

compile 'com.google.code.gson:gson:2.8.0'

像这样解析数据

Gson gson = new Gson(); 数据data= gson.fromJson(json,Data.class);

这是数据类

     public class Data {

@SerializedName("id")
@Expose
public int id;
@SerializedName("name")
@Expose
public String name;
@SerializedName("ingredients")
@Expose
public List<Ingredient> ingredients = null;
@SerializedName("steps")
@Expose
public List<Step> steps = null;
@SerializedName("servings")
@Expose
public int servings;
@SerializedName("image")
@Expose
public String image;

}

这是 Ingredient 类

public class Ingredient {

@SerializedName("quantity")
@Expose
public int quantity;
@SerializedName("measure")
@Expose
public String measure;
@SerializedName("ingredient")
@Expose
public String ingredient;

}

这是Step类

public class Step {

@SerializedName("id")
@Expose
public int id;
@SerializedName("shortDescription")
@Expose
public String shortDescription;
@SerializedName("description")
@Expose
public String description;
@SerializedName("videoURL")
@Expose
public String videoURL;
@SerializedName("thumbnailURL")
@Expose
public String thumbnailURL;

}

关于java - 如何在 JSONArray 中正确嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44546516/

相关文章:

java - 还有其他方法可以加载吗?

可比较的Java实例

javascript - 检查包含数组的数组

java - 如果我创建了一个 BufferedReader 实例,其参数为 FileReader,我必须关闭哪一个?

Java正则表达式获取双引号之间的字符

Android 无法禁用剪切复制粘贴

android - Webview + 滚动问题 + android

java - 寻找音频信号中的峰值频率?

java - 如何使用 RxJava TestObserver 断言两个字符串列表?

javascript - 如何将 JSON 数组转换为 Javascript 数组?