【问题标题】:Error: Could not cast value of type .. in JSON错误:无法在 JSON 中转换类型 .. 的值
【发布时间】:2015-10-25 15:46:37
【问题描述】:

我想做一个关于天气的简单应用。

import Foundation

let getWeatherInfoUrl = NSURL(string: "http://www.weather.com.cn/adat/sk/101280601.html")
let weatherInfo = NSData(contentsOfURL:getWeatherInfoUrl!)
if weatherInfo != nil
    {
    print(weatherInfo!) 
    let json: NSData = try! NSJSONSerialization.JSONObjectWithData(weatherInfo!, options: NSJSONReadingOptions.AllowFragments) as! NSData
    }else{
    print("error")
    }

这段代码主要是从url获取数据,然后改成JSON。

它可以运行,但调试区域显示:

如何解决此错误?

【问题讨论】:

标签: swift swift2


【解决方案1】:

您收到的错误是因为您将 json 转换为 NSData,但是根据解析数据,它应该是 NSArrayNSDictionary。您可以尝试使用以下代码,它为您提供 NSDictionary 对象作为 json 并且您可以进一步操作以获取所需的信息。

let getWeatherInfoUrl = NSURL(string: "http://www.weather.com.cn/adat/sk/101280601.html")!
if let weatherInfo = NSData(contentsOfURL:getWeatherInfoUrl) {
    print(weatherInfo)
    let json = try! NSJSONSerialization.JSONObjectWithData(weatherInfo, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
}
else{
    print("error")
}

【讨论】:

  • 但是我想从 JSON 中获取一些数据,当我编写 'let info = json.objectForKey("weatherinfo")' 时,它会注意到 使用未解析的标识符'JSON'。那么我该如何解决这个错误。你能帮我吗?
  • @B.Steven,您需要在访问它之前包装 json。 let info = json!.objectForKey("weatherinfo") 这会起作用
猜你喜欢
  • 2017-11-25
  • 2017-05-21
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2017-10-21
  • 1970-01-01
相关资源
最近更新 更多