簡體   English   中英

Swift和JSON僅解析對象而不是數組

[英]Swift and JSON parsing only an object not an array

我正在開發一個氣象應用程序,該應用程序分析JSON數據並將標簽文本設置為JSON請求的臨時值。 我從天氣對象數組中獲得了id的值,但是臨時數組中沒有溫度,它只是一個對象。 有人可以告訴我我哪里錯了。 我的價值是零,因為我沒有正確獲取它。 這是我的代碼段和JSON。

@IBAction func getWeather(sender: AnyObject) {
        let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=MYAPPID")!
        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 {

                            //this works
                            let id = weather["id"]?.stringValue
                            self.trumpDescription.text=id;
                            print(id)

                            //this is where I am confused it changes from an array to just an object
                            let temp = json["temp"] as? String
                            self.currentTempView.text=temp;
                            print(temp)
                        }

                    }

                }

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

            }
        }

        task.resume()
    }`

這是JSON:

{
    "coord": {
    "lon": 138.93,
    "lat": 34.97
    },
    "weather": [
    {
    "id": 803,
    "main": "Clouds",
    "description": "broken clouds",
    "icon": "04n"
    }
    ],
    "base": "cmc stations",
    "main": {
    "temp": 292.581,
    "pressure": 1019.48,
    "humidity": 99,
    "temp_min": 292.581,
    "temp_max": 292.581,
    "sea_level": 1028.92,
    "grnd_level": 1019.48
    },
    "wind": {
    "speed": 5.36,
    "deg": 237.505
    },
    "clouds": {
    "all": 64
    },
    "dt": 1464964606,
    "sys": {
    "message": 0.0037,
    "country": "JP",
    "sunrise": 1464895855,
    "sunset": 1464947666
    },
    "id": 1851632,
    "name": "Shuzenji",
    "cod": 200
    }

看起來應該是

if let main = json["main"] as? NSDictionary {
    let temp = main["temp"] as! String
    print(temp)
}

代替這個:
let temp = json["temp"] as? String

嘗試這個:

if let main = json["main"] as? [String: AnyObject] {
    let temp = main[temp]?.stringValue
    print(temp)

    //alternatively you can try this as per your convenience of data type
    let tempNew = main[temp]?.doubleValue
    print(tempNew) 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM