一尘不染

如何在Swift中将JSON数组解析为数组

swift

我正在尝试解析如下的JSON

    [
     {
     "People": [
                  "Jack",
                  "Jones",
                  "Rock",
                  "Taylor",
                  "Rob"
                  ]
     },
     {
     "People": [
          "Rose", 
          "John"

        ]
      },
      {
        "People": [
          "Ted"
        ]
      }
]

到[[“ Jack”,“ Jones”,“ Rock”,“ Taylor”,“ Rob”],[“ Rose”,“ John”],[“ Ted”]]的数组

这是数组的数组。

我尝试了下面的代码

if let path = Bundle.main.path(forResource: "People", ofType: "json")
        {

            let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [AnyObject]
            for people in peoplesArray! {
              print(people)
            }

        }

当我打印“人”时,我得到o / p为

{
    People =     (
        Jack,
        "Jones",
        "Rock",
        "Taylor",
        "Rob"
    );
}
{
    People =     (
        "Rose",
        "John"
    );
}
 .....

我很困惑当“人物”重复3次时如何解析

尝试在UITableView中显示内容,其中第一个单元格具有“ Jack” ..“ Rob”,第二个单元格具有“ Rose”,“
John”,第三个单元格为“ Ted”

请帮助我了解如何实现这一目标


阅读 475

收藏
2020-07-07

共1个答案

一尘不染

 var peoplesArray:[Any] = [
    [
        "People": [
        "Jack",
        "Jones",
        "Rock",
        "Taylor",
        "Rob"
        ]
    ],
    [
        "People": [
        "Rose",
        "John"

        ]
    ],
    [
        "People": [
        "Ted"
        ]
    ]
  ]

 var finalArray:[Any] = []

 for peopleDict in peoplesArray {
    if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
        finalArray.append(peopleArray)
    }
 }

 print(finalArray)

输出:

[["Jack", "Jones", "Rock", "Taylor", "Rob"], ["Rose", "John"], ["Ted"]]

在您的情况下,它将是:

if let path = Bundle.main.path(forResource: "People", ofType: "json") {
    let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [Any]

    var finalArray:[Any] = []

    for peopleDict in peoplesArray {
        if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
            finalArray.append(peopleArray)
        }
    }

    print(finalArray)
}
2020-07-07