Swift JSON解析

扫码查看
本文介绍了Swift JSON解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iOS天气应用程序,需要一些帮助来获取JSON的一些值.我正在尝试在天气对象中提取id的值.调试时,我得到的值为nil.有人能帮我解释一下逻辑吗?这是JSON请求和Swift代码.

I am working on an iOS weather app and need some help getting some values with JSON. I am trying to pull the value of id in the weather object. I am getting a value of nil when I debug. Could someone please help me with the logic? Here is the JSON request and Swift code.

{
    "coord":{
        "lon":138.93,
        "lat":34.97
    },
    "weather":[
        {
            "id":800,
            "main":"Clear",
            "description":"clear sky",
            "icon":"01n"
        }
    ],
    "base":"cmc stations",
    "main":{
        "temp":292.181,
        "pressure":1005.21,
        "humidity":100,
        "temp_min":292.181,
        "temp_max":292.181,
        "sea_level":1014.59,
        "grnd_level":1005.21
    },
    "wind":{
        "speed":3.41,
        "deg":78.0005
    },
    "clouds":{
        "all":0
    },
    "dt":1464801034,
    "sys":{
        "message":0.003,
        "country":"JP",
        "sunrise":1464723086,
        "sunset":1464774799
    },
    "id":1851632,
    "name":"Shuzenji",
    "cod":200
}

这是我的Swift代码段:

Here is my Swift snippet:

    let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=6361e893fa064b1bfeaca686cd0929cc")!
            let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithRequest(urlRequest) {
                (data, response, error) -> Void in

                let httpResponse = response as! NSHTTPURLResponse
                let statusCode = httpResponse.statusCode

                if (statusCode == 200) {
                    print("JSON Downloaded Sucessfully.")

                    do{

                        let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                        if let today = json["weather"] as? [[String: AnyObject]] {
                            //this is pulling 4 key value pairs
                            for weather in today {

                                let id = weather["id"] as? String


                                self.trumpDescription.text=id;
                                print(id)

                                    }

                                }
                            }

                    catch {
                        print("Error with Json: \(error)")
                    }

                }
            }

            task.resume()
        }

推荐答案

在您的代码中尝试以下操作:
let id = weather["id"]?.stringValue

try this in your code:
let id = weather["id"]?.stringValue

代替此:
let id = weather["id"] as? String

看看魔术!

编辑以解释:
当这个答案对您有用时,让我告诉您它为什么这样做.
id是作为整数从服务器端发送的.当您执行weather["id"]时,它将返回类型为AnyObject?的对象.当您执行weather["id"] as? String时,转换失败,因此您将获得零分.

Edit for explanation:
As this answer worked for you, let me tell you why it did.
The id is being sent as integer from the server side. When you do weather["id"] it returns object of type AnyObject?. When you do weather["id"] as? String the casting fails thus you were getting nil.

这篇关于Swift JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 03:57
查看更多