循环遍历 JSON 文件 - android

Looping through a JSON File - android

作为一项小任务的一部分,我目前正在制作一个应用程序来订餐。我有一个 JSON 文件,当您转到 select 您想要的餐点时,它会被读取。但是我需要一个可以遍历 JSON 文件的 for 循环。

JSON 文件

[
  {
    Name: "No Meal Selected",
    SandPrice: "0.00",
    RegPrice: "0.00"
  },
  {
    Name: "OFFER (See Notes)",
    SandPrice: "3.79",
    RegPrice: "5.29"
  },
  {
    Name: "Whopper",
    SandPrice: "3.79",
    RegPrice: "5.29"
  },
  {
    Name: "Double Whopper",
    SandPrice: "4.79",
    RegPrice: "6.29"
  },
  {
    Name: "Whopper Junior",
    SandPrice: "2.19",
    RegPrice: "3.69"
  },
  {
    Name: "Whopper Bacon And Cheese",
    SandPrice: "4.59",
    RegPrice: "6.09"
  },
  {
    Name: "Angus XT Steakhouse",
    SandPrice: "5.59",
    RegPrice: "7.09 "
  },
  {
    Name: "Angus XT Classic",
    SandPrice: "5.09",
    RegPrice: "6.59 "
  },
  {
    Name: "Angus XT Smoked Bacon And Cheddar",
    SandPrice: "5.59",
    RegPrice: "7.09 "
  },
  {
    Name: "Angus Steakhouse",
    SandPrice: "4.99",
    RegPrice: "6.49 "
  },
  {
    Name: "Angus Classic",
    SandPrice: "4.49",
    RegPrice: "5.99 "
  },
  {
    Name: "Angus Smoked Bacon And Cheddar",
    SandPrice: "4.99",
    RegPrice: "6.49 "
  },
  {
    Name: "Angus Steakhouse Double",
    SandPrice: "5.99",
    RegPrice: "7.49 "
  },
  {
    Name: "Angus Classic Double",
    SandPrice: "5.49",
    RegPrice: "6.99 "
  },
  {
    Name: "Angus Smoked Bacon And Cheddar Double",
    SandPrice: "5.99",
    RegPrice: "7.49 "
  }
]


^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
JSON i need to loop through

如果有人可以帮助我,那将非常有帮助,

谢谢。

JSONArray items = jsonObj.getJSONArray("nameOfArray");

for(int i = 0; i < items.length(); i++)
{
    JSONObject item = items.getJSONObject(i);
    //...
}

您提供的 JSON 格式不正确。 首先,JSON 文件应该以对象开头,而不是数组:

{"Array":[*contents of your array*]}

其次,每个 object/array 名称应该是一个字符串 - 这意味着在引号中:

{
    "Name": "Angus Smoked Bacon And Cheddar",
    "SandPrice": "4.99",
    "RegPrice": "6.49"
}

详情请参考The JSON Data Interchange Format

然后您可以使用以下模板从数组中获取 JSON 个对象:

JSONArray array = new JSONObject(myFileContents).getJSONArray("Array");
for (int i = 0; i < array.length(); i++) {
    JSONObject object = array.getJSONObject(i);
    // . . . work with object
}