循环通过JSON文件 - android

时间:2015-01-19 11:07:09

标签: android json for-loop

我目前正在制作一个应用程序来订购膳食作为一项小任务的一部分。我有一个JSON文件,当您进入微调器选择您想要的餐时,会读取该文件。但是我需要一个可以遍历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

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

谢谢。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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

其次,每个对象/数组名称应该是一个String - 这意味着用引号:

{
    "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
}