How to parse Array of JSON to array in Swift

后端 未结 5 684
南方客
南方客 2020-12-05 12:02

I\'m trying to parse JSON which is like below

[
  {
    "People": [
      "Jack",
      "Jones",
      "Rock",
      &         


        
5条回答
  •  甜味超标
    2020-12-05 12:42

    You can do this in an elegant and type safe way leveraging Swift 4 Decodable

    First define a type for your people array.

    struct People {
      let names: [String]
    }
    

    Then make it Decodable, so that it can be initialised with a 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)
      }
    }
    

    Now you can easily decode your JSON input

    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
    }
    

    Finally to get get your linear array of names you can do

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

提交回复
热议问题