在Swift 3中将JSON下载到表视图中

时间:2017-01-25 13:58:13

标签: json swift swift3

我想在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 {

5 个答案:

答案 0 :(得分:1)

您的JSON响应属于Array类型而不是Dictionary。在Swift中使用本机Array而不是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()
    }

}

注意:您需要使用自定义对象或字典的单个数组,而不是使用多个数组,所以如果您创建一个自定义类并创建它的数组或使用字典数组,那就更好了。

答案 1 :(得分:1)

我已经解决了问题..我偶然发现了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 {
                        }
                    }

答案 2 :(得分:0)

我重新使用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 :(得分:0)

第一个json的根元素是Dictionary,所以你的代码适用于第一种json格式。但是你想解析根元素的第二个json是数组,你试图将数组分配到字典中,这就是为什么你出错了所以只需用你的代码替换..

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

答案 4 :(得分:0)

更改

as! NSDictionary

as! [String : Any]