【问题标题】:Downloading JSON into Table View in Swift 3在 Swift 3 中将 JSON 下载到表视图中
【发布时间】:2017-01-25 13:58:13
【问题描述】:

我想在 tableview 中显示我的数据,我有一个 json 数据,我已经看过这个 tutorial。它正在工作,但我的 json 数据没有数组键“actor”。 这是示例的 json 数据。

{
  "actors": [
    {
      "name": "Brad Pitt",
      "description": "William Bradley 'Brad' Pitt is an American actor and film producer. He has received a Golden Globe Award, a Screen Actors Guild Award, and three Academy Award nominations in acting categories",
      "dob": "December 18, 1963",
      "country": "United States",
      "height": "1.80 m",
      "spouse": "Jennifer Aniston",
      "children": "Shiloh Nouvel Jolie-Pitt, Maddox Chivan Jolie-Pitt",
      "image": "http://microblogging.wingnity.com/JSONParsingTutorial/brad.jpg"
    },
    {
      "name": "Tom Cruise",
      "description": "Tom Cruise, is an American film actor and producer. He has been nominated for three Academy Awards and has won three Golden Globe Awards. He started his career at age 19 in the 1981 film Endless Love.",
      "dob": "July 3, 1962",
      "country": "United States",
      "height": "1.70 m",
      "spouse": "Katie Holmes",
      "children": "Suri Cruise, Isabella Jane Cruise, Connor Cruise",
      "image": "http://microblogging.wingnity.com/JSONParsingTutorial/cruise.jpg"
    }
  ]
}

这是我的 json 数据。

[
      {
        "ID": 1,
        "name": "Amy"
      {
        "ID": 2,
        "name": "John"
      }
    ]

这是我的代码;

func downloadJsonWithURL() {

    let url = NSURL(string: urlString)
    URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            print(jsonObj!.value(forKey: "actors"))

            if let studentArray = jsonObj!.value(forKey: "actors") as? NSArray {
                for student in studentArray{
                    if let studentDict = student as? NSDictionary {

                        if let name = studentDict.value(forKey: "ID") {
                            self.noArray.append(name as! String)
                        }
                        if let name = studentDict.value(forKey: "name") {
                            self.adiArray.append(name as! String)
                        }
                    }
                }
            }

            OperationQueue.main.addOperation({
                self.tableView.reloadData()
            })
        }
    }).resume()
}

我这里有问题; enter image description here

这将是一个问题:/

        // my json data doesnt have "actors" ?????
        print(jsonObj!.value(forKey: "actors"))
        if let studentArray = jsonObj!.value(forKey: "actors") as? NSArray {
            for student in studentArray{
                if let studentDict = student as? NSDictionary {

【问题讨论】:

  • 不要强制解包!

标签: json swift swift3


【解决方案1】:

您的 JSON 响应是 Array 类型而不是 Dictionary。在 Swift 中使用原生数组而不是 NSArray。因此,您需要将jsonObject 结果类型转换为[[String:Any]]

if let array = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [[String:Any]] {
    //Now loop through the array.
    for item in array {
        if let id = item["ID"] as? Int {
            self.noArray.append("\(id)")
        }
        if let name = item["name"] as? String {
           self.adiArray.append(name)
        }
    }
    DispatchQueue.main.async {
        self.tableView.reloadData()
    }

}

注意:您需要使用自定义对象或字典的单个数组,而不是使用多个数组,因此如果您创建一个自定义类并将其制作为数组或使用字典数组,则会失败。 p>

【讨论】:

    【解决方案2】:

    我推荐使用 SwiftyJSON:https://github.com/SwiftyJSON/SwiftyJSON。使用 cocoapods 轻松安装:pod 'SwiftyJSON'

    import SwiftyJSON
    
    URLSession.shared.dataTask(with: URL(string: "asd")!, completionHandler: {(data, response, error) in
    
                guard error == nil else {
    
                    print("there is an error \(error)")
                    return
                }
    
                guard data != nil else {
    
                    print("there is no data")
                    return
                }
    
                let json = JSON(data: data)
    
                for actor in json["actors"].array {
    
                    self.noArray.append(actor["ID"].int)
                    self.adiArray.append(actor["name"].string)
                }
    
                DispatchQueue.main.async {
    
                    self.tableView.reloadData()
                }
    
            }).resume()
    

    【讨论】:

      【解决方案3】:

      第一个 json 的根元素是 Dictionary,因此您的代码适用于第一个 json 格式。但是您要解析的具有根元素的第二个 json 是数组,并且您正在尝试将数组分配到字典中,这就是您遇到错误的原因所以只需将您的代码替换为 ..

      if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options:[]) as? NSArray 
      

      【讨论】:

        【解决方案4】:

        改变

        as! NSDictionary
        

        as! [String : Any]
        

        【讨论】:

          【解决方案5】:

          我已经解决了问题..我偶然发现了 jsonObj 的线路并关闭了演员的线路

          这个;

          if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray {}
          

          还有这个

          if let actorArray = jsonObj!.value(forKey: "actors") as? NSArray {
                              for student in jsonObj!{
                                  if let studentDict = student as? NSDictionary {
                                  }
                              }
          

          【讨论】:

          • 您的 JSON 中没有像演员那样的东西,那么您是如何使用它的,在您的问题中,您已经告诉演员使用教程 JSON,这没有任何意义。同样在 Swift 中,您需要使用原生数组和字典,就像我的 answer
          猜你喜欢
          • 2017-10-06
          • 1970-01-01
          • 1970-01-01
          • 2023-04-07
          • 2021-10-30
          • 1970-01-01
          • 2018-05-14
          • 1970-01-01
          • 2017-06-15
          相关资源
          最近更新 更多