【问题标题】:Error in JSON downloaded data as NSDictionary in Swift在 Swift 中将 JSON 下载数据作为 NSDictionary 出错
【发布时间】:2014-11-30 00:44:50
【问题描述】:
@IBOutlet weak var weather: UILabel!
@IBOutlet weak var city: UITextField!
@IBAction func button(sender: AnyObject) {
    let urlpath = "api.worldweatheronline.com/free/v2/weather.ashx?q=\(city.text)&format=json&num_of_days=5&key=c7fc4c9444ae2ddcee02a0893d5f0"
    let url = NSURL(string: urlpath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            self.weather.text="error"


        }else{

            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
            println(jsonResult)

        }


    })
    task.resume()





}

运行应用程序时,我在控制台中收到错误消息。我正确地序列化了我相信的数据,但是我无法让 JSON 序列化数据显示在 NSDictionary 中。我试图将字典打印到控制台,但它仍然只是显示为错误。请帮助我理解这里出了什么问题。

【问题讨论】:

  • 这是一个严重的问题:error: nil)
  • “我在控制台中收到错误”——这是一个无用的声明。您必须准确引用错误。如果您想将 JSON 数据放入字典中,则必须对其进行反序列化。
  • JSON 是什么样的?
  • JSON 是什么样的?

标签: json swift nsdictionary


【解决方案1】:

尝试这样的事情。

   func fetchWeatherData(latLong: String, completion: WeatherDataCompletionBlock) {

    let baseUrl = NSURL(string: "http://api.worldweatheronline.com/free/v2/weather.ashx?q=\(city.text)&format=json&num_of_days=5&key=c7fc4c9444ae2ddcee02a0893d5f0")
    let request = NSURLRequest(URL: baseUrl!)
    println(request)
    let task = session.dataTaskWithRequest(request) {[unowned self] data, response, error in
        if error == nil {
            var jsonError: NSError?
            if (jsonError == nil) {
                let weatherDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &jsonError) as NSDictionary

                let data = WeatherData(weatherDictionary: weatherDictionary)
                completion(data: data, error: nil)
            } else {
                completion(data: nil, error: jsonError)
            }
        } else {
            completion(data: nil, error: error)
        }
    }

    task.resume()
}

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    相关资源
    最近更新 更多