swift如何得到一个复杂的 JSON 对象值

发布时间: 2017/3/5 22:05:11
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

它可能是有人能给我如何获取这些比萨店的名称打印出来吗?我的应用程序打印出预期 "Status Code: 200" 。然而,我的控制台仅显示空方括号括 [] 。我怀疑,我不够努力值从我 JSON 对象正确。

我为我的 API 使用此链接。

API 的链接

问题

如何能正确取值从我序列化 JSON 对象?

相关代码︰

    // Response
    if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200, let data = data {
        print("Status Code: \(httpResponse.statusCode)")



        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)

            if let pizzaPlaces = json["response"] as? [[String: AnyObject]] {
                for place in pizzaPlaces {
                    if let name = place ["name"] as? String {
                        self.PizzaClass.append(name)
                    }
                }
            }
        } catch {
            print("Error Serializing JSON Data: \(error)")
        }
        print(self.PizzaClass)


    }
}).resume()

解决方法 1:

你需要投你 NSJSONSerialization.JSONObjectWithData 结果为 [String:AnyObject]

    let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]

一旦你有所有你需要做是要注意你的投射。考虑下面的示例的代码。如果我们想要我们 response 对象使用 jsonObject["response"] 我们有什么样的数据结构?

"response": {
        "venues": [{
            //... continues
        }]
    } 

在左边我们有 "response" 这是一个字符串,在我们的右边 {}AnyObject 。所以我们有 [String: AnyObject] 。你只需要想想什么对象你一块一块的处理。下面是一个实例,你可以只是将其粘贴到您的应用程序。

全工作代码︰

func getJson() {

    let request = NSMutableURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search?client_id=0F5M0EYOOFYLBXUOKTFKL5JBRZQHAQF4HEM1AG5FDX5ABRME&client_secret=FCEG5DWOASDDYII4U3AAO4DQL2O3TCN3NRZBKK01GFMVB21G&v=20130815%20&ll=29.5961,-104.2243&query=burritos")!)
    let session = NSURLSession.sharedSession()

    request.HTTPMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

        guard let testResponse = response as? NSHTTPURLResponse else {
            print("\(response)")
            return
        }

        guard let status = HTTPStatusCodes(rawValue: testResponse.statusCode) else {
            print("failed to unwrap status")
            return
        }
        print(status)

        switch status {
        case .Created:
            print("ehem")
        case .BadRequest:
            print("bad request")
        case .Ok:
            print("ok")

            guard let returnedData = data else {
                print("no data was returned")
                break
            }
            do {
                let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]

                guard let response = jsonObject["response"] as? [String: AnyObject] else { return }     
                guard let venues = response["venues"] as? [AnyObject] else { return }
                guard let location = venues[0]["location"] as? [String:AnyObject] else { return }
                guard let formattedAddress = location["formattedAddress"] else { return }

                print("response: \n\n \(response)\n------")
                print("venues : \n\n \(venues)\n-------")
                print("location : \n\n \(location)\n------")
                print("formatted address : \n \(formattedAddress)")

            } catch let error {
                print(error)
            }

            // update user interface
            dispatch_sync(dispatch_get_main_queue()) {
                print("update your interface on the main thread")
            }
        }  
    }
    task.resume()
}

这无论是在其自己的文件放置我们外面的类声明中,

  enum HTTPStatusCodes : Int {
        case Created = 202
        case Ok = 200
        case BadRequest = 404 
    }
赞助商