如何获取 Java for 循环以提取所选条件中的所有 API 记录



我是一个有抱负的Android开发人员。我在创建应用程序方面还没有很多经验。

我有一个 API,以及调用和检索数据的代码。我遇到的问题是它只是拉出第一张唱片。当我运行调试工具时,我可以看到它找到了所有三个,但它只打印了第一个。非常感谢任何帮助和指导。

这是我的代码:

JSONObject parentObject = new JSONObject(finalJson);
                JSONObject reportObject = parentObject.getJSONObject("report");
                String mReport = reportObject.getString("foods");
                JSONArray foodArray = reportObject.getJSONArray("foods");
                JSONObject mFood = foodArray.getJSONObject(0);
                String foodName = mFood.getString("name");
                String foodMeasure = mFood.getString("measure");
                JSONArray nutrientsArray = mFood.getJSONArray("nutrients");
                for(int i = 0; i < nutrientsArray.length(); ++i) {
                JSONObject nutrientObject = nutrientsArray.getJSONObject(i);
                String nutrientName = nutrientObject.getString("nutrient");
                String nutrientValue = nutrientObject.getString("value");
                return foodName + "nNutrient:  " + nutrientName + "nMeasure: " + foodMeasure + "nValue: " + nutrientValue;
            }

以下是 API 数据:

API 数据库链接

{
   "report": {
 "sr": "Legacy",
"groups": "All groups",
"subset": "All foods",
"end": 150,
"start": 0,
"total": 7524,
"foods": [
{
"ndbno": "09427",
"name": "Abiyuch, raw",
"weight": 114,
"measure": "0.5 cup",
"nutrients": [
{
"nutrient_id": "203",
"nutrient": "Protein",
"unit": "g",
"value": "1.71",
"gm": 1.5
},
{
"nutrient_id": "204",
"nutrient": "Total lipid (fat)",
"unit": "g",
"value": "0.11",
"gm": 0.1
},
{
"nutrient_id": "205",
"nutrient": "Carbohydrate, by difference",
"unit": "g",
"value": "20.06",
"gm": 17.6
}
]
},

这是我的结果(它们被正确解析(

foodName:"Abiych, raw" nutrientName: "Protein" foodMeasure: "0.5 cup" nutrientValue: "1.74"

如何让它从 API 中提取和显示调用的其他两个项目?

非常感谢!

您的for循环有一个 return 语句。它在第一次迭代后退出for循环和方法。将结果存储在数组中,并将数组从for循环中返回。

我能够使用它来解决它。for 循环执行答案帮助我看到了我的错误。谢谢!

StringBuffer finalBufferedData = new StringBuffer();
                        for(int i = 0; i < nutrientsArray.length(); ++i) {
                        JSONObject nutrientObject = nutrientsArray.getJSONObject(i);
                        String nutrientName = nutrientObject.getString("nutrient");
                        String nutrientValue = nutrientObject.getString("value");
                        finalBufferedData.append( "nNutrient:  " + nutrientName +
                                "nMeasure: " + foodMeasure + "nValue: " + nutrientValue +"n "+"n ");

                    }
                    return foodName + "n" + finalBufferedData.toString();

最新更新