因此,我正在构建一个食谱应用程序。我现在想在TextView对象的列表中显示成分。

下面的代码是我目前的做法。成分(in IngredientLines中)仅放入字符串中。

JSONObject obj = new JSONObject(response);
JSONArray hits = obj.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
    JSONObject a = hits.getJSONObject(i);
    JSONObject recipe = a.getJSONObject("recipe");
    ListItem item = new ListItem(
        recipe.getString("label"),
        recipe.getString("source"),
        recipe.getString("image"),
        recipe.getString("ingredientLines"),
        recipe.getString("url")
    );
}


这是现在字符串的样子

"ingredientLines" : [ "1 pound multigrain spaghetti (recommended: Barilla Plus)", "Kosher salt", "2 teaspoons black peppercorns", "3 tablespoons unsalted butter", "1 cup coarsely grated Pecorino Romano cheese", "2 full handfuls baby arugula, roughly chopped" ]


我希望它看起来像

"1 pound multigrain spaghetti (recommended: Barilla Plus)\n Kosher..."


这是我从中解析的JSON

"recipe" : {
    "uri" : "http://www.edamam.com/ontologies/edamam.owl#recipe_7a38f039e2a9d3df25e65cc64bc0f87d",
    "label" : "The Secret Ingredient (Black Pepper): Multigrain Cacio e Pepe with Arugula Recipe",
    "image" : "https://www.edamam.com/web-img/f59/f59ec1a536535e9072bbf9a7c2432779.jpg",
    "source" : "Serious Eats",
    "url" : "http://www.seriouseats.com/recipes/2011/02/the-secret-ingredient-black-pepper-multigrain-cacio-e-pepe.html",
    "shareAs" : "http://www.edamam.com/recipe/the-secret-ingredient-black-pepper-multigrain-cacio-e-pepe-with-arugula-recipe-7a38f039e2a9d3df25e65cc64bc0f87d/pep",
    "yield" : 4.0,
    "dietLabels" : [ "Balanced" ],
    "healthLabels" : [ "Sugar-Conscious", "Vegetarian", "Peanut-Free", "Tree-Nut-Free", "Alcohol-Free" ],
    "cautions" : [ ],
    "tags" : [ "pasta", "pepper", "The Secret Ingredient", "vegetarian" ],
    "ingredientLines" : [ "1 pound multigrain spaghetti (recommended: Barilla Plus)", "Kosher salt", "2 teaspoons black peppercorns", "3 tablespoons unsalted butter", "1 cup coarsely grated Pecorino Romano cheese", "2 full handfuls baby arugula, roughly chopped" ]
}

最佳答案

使用String.join("\n", ingredientLines)将数组转换为项目之间带有“ \ n”的字符串。

因此,使用recipe.getString("ingredientLines")代替:

String.join("\n", recipe.getJSONArray("ingredientLines"))

07-26 04:57