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

17

我正在尝试解析以下格式的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)
    }
}

当我打印"people"时,输出结果为:

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

我不知道如何解析"People"连续出现3次的情况。

我正在尝试在UITableView中显示内容,其中第一个单元格包含“Jack”..“Rob”,第二个单元格包含“Rose”,“John”,第三个单元格包含“Ted”。

请帮助我理解如何实现这一点。

5个回答

18

您可以利用 Swift 4 的Decodable来优雅且类型安全地完成此操作。

首先为您的人员数组定义一个类型。

struct People {
  let names: [String]
}

然后使它成为 Decodable,这样就可以使用 JSON 进行初始化。

extension People: Decodable {

  private enum Key: String, CodingKey {
    case names = "People"
  }

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Key.self)

    self.names = try container.decode([String].self, forKey: .names)
  }
}

现在,您可以轻松解码JSON输入了

guard
  let url = Bundle.main.url(forResource: "People", withExtension: "json"),
  let data = try? Data(contentsOf: url)
else { /* Insert error handling here */ }

do {
  let people = try JSONDecoder().decode([People].self, from: data)
} catch {
  // I find it handy to keep track of why the decoding has failed. E.g.:
  print(error)
  // Insert error handling here
}

最后,要获取名称的线性数组,您可以执行以下操作

let names = people.flatMap { $0.names }
// => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]

如何在SwiftyJSON中使用,而不需要Codable。 - kiran
@kiran 很抱歉我不知道如何使用 SwiftyJSON 实现。我建议你考虑迁移到 Decodable,这样可以摆脱第三方依赖。 - mokagio
这是一个很好的、干净的答案。巧妙地使用了 do/catch 循环来避免使用崩溃操作符(!)。 - FontFamily

14
 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)
}

1

这里有一个由3个对象组成的数组。每个对象都是一个字典,其中键为people,值为字符串数组。当您尝试进行JSON序列化时,必须将其转换为预期结果。因此,您首先有一个对象数组,然后是一个String: Any字典,最后获得一个字符串数组。

let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as? [AnyObject]
guard let peoplesObject = peoplesArray["people"] as? [[String:Any]] else { return }
for people in peoplesObject {
    print("\(people)")
}

当我执行时,在"peoplesObject"中我得到了nil。我的JSON是正确的,但不确定原因。 - Ashh
你的 JSON 数据是在应用内部还是从网络响应中获取的?由于 try 后面有一个感叹号,你可能会得到 nil,但我不确定。 - anckydocky
看,这是我成功解析来自LastFM的JSON响应的示例。 - anckydocky

1

我无法把它粘贴到评论中,可能因为它太长了或者其他原因

static func photosFromJSONObject(data: Data) -> photosResult {
    do {
        let jsonObject: Any =
                try JSONSerialization.jsonObject(with: data, options: [])

        print(jsonObject)

        guard let
              jsonDictionary = jsonObject as? [NSObject: Any] as NSDictionary?,
              let trackObject = jsonDictionary["track"] as? [String: Any],
              let album = trackObject["album"] as? [String: Any],
              let photosArray = album["image"] as? [[String: Any]]
                else {
            return .failure(lastFMError.invalidJSONData)
        }
    }
}

而JSON大致如下:
{
  artist: {
    name: Cher,
    track: {
        title: WhateverTitle,
        album: {
          title: AlbumWhatever,
          image: {
             small: "image.px",
             medium: "image.2px",
             large: "image.3px"}
       ....

1
假设JSON是编码数据。
var arrayOfData : [String] = []
dispatch_async(dispatch_get_main_queue(),{
    for data in json as! [Dictionary<String,AnyObject>]
    {
        let data1 = data["People"]

        arrayOfData.append(data1!)
    }
})

你现在可以使用arrayOfData。 :D


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接