【问题标题】:How to parse Array of JSON to array in Swift如何在 Swift 中将 JSON 数组解析为数组
【发布时间】:2017-06-24 04:23:47
【问题描述】:

我正在尝试解析如下所示的 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”时,我得到 o/p as

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

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

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

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

【问题讨论】:

    标签: ios arrays json swift


    【解决方案1】:

    这里首先是一个由 3 个对象组成的数组。每个对象都是一个字典,其中键是人,值是字符串数组。当您尝试进行 jsonserialization 时,您必须将其转换为预期的结果。所以你首先有一个对象数组,然后你有一个带有 String: Any 的字典,然后你得到一个 String 数组

    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 是正确的,但不知道为什么
    • 您的应用程序中是否有您的 json,或者您将其作为来自网络的响应?你可能因为 !从尝试,但我不确定
    • 看,这是我如何设法解析来自 LastFM 的 JSON 响应的示例
    【解决方案2】:

    我无法将其粘贴到评论中,它太长或其他什么

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

    【讨论】:

      【解决方案3】:
       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)
      }
      

      【讨论】:

        【解决方案4】:

        假设 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

        【讨论】:

          【解决方案5】:

          您可以利用 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 中拥有它!没有编码
          • @kiran 我不知道如何在SwiftyJSON 中做到这一点,抱歉。不过,我建议投资迁移到 Decodable。这样,您将摆脱第三方依赖。
          • 这是一个很好的、干净的答案。充分利用 do/catch 循环来避免使用崩溃运算符 (!)。
          猜你喜欢
          • 2017-02-07
          • 2020-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多