我从一个json数据对象解析后,很难从NSDictionary对象中提取值。 ![在此输入图像说明] [1]
var stationsInfo: NSArray = stationsDictionary["stations"]! as NSArray
for aStation in stationsInfo{
//parse the information
var station = aStation as NSDictionary
println("next")
var example: NSDictionary = ["key": "val", "key2": "val2", "key3": "val3"]
var ex: String = example["key2"] as String
println(station)
var age_in_days : Double = station["age_in_days"] as Double
var hight_normal: Double = station["height_nom"] as Double
var hight_over : Double = station["height_ovr"] as Double
var latitude: CLLocationDegrees = station["lat"] as Double
var longitude: CLLocationDegrees = station["lon"] as Double
var station_id : Int = station["station_id"] as Int
var ex最终等于" val2"因为它可以工作,但当我试图获取存储在电台词典中的值时,我会一直遇到奇怪的错误。
尽管电台的价值如下,但仍然会发生这种情况
{ " age_in_days" = 1401753600; " height_nom" =" 13.5&#34 ;; " height_ovr" =" 14.0&#34 ;; lat =" 24.084082&#34 ;; lon =" 89.023476&#34 ;; " station_id" = 1; }
答案 0 :(得分:0)
您可以尝试将其转换为Swift词典。你知道关键和价值是什么吗?如果是这样,请将AnyObjects替换为这些类型。你可以试试任何AnyObject,但你可能不得不做其他的转换。
var station = aStation as [AnyObject:AnyObject]
答案 1 :(得分:0)
我发现了什么问题!
显然,默认情况下,所有JSON值都是string类型。
{ “age_in_days”= 1401753600; “height_nom”=“13.5”; “height_ovr”=“14.0”; lat =“24.084082”; lon =“89.023476”; “station_id”= 1; }
因此,获取double值的正确方法是:
var dataDictionary = NSJSONSerialization.JSONObjectWithData(dataInput, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
var stationsInfo: NSArray = stationsDictionary["stations"]! as NSArray
for station in stationsInfo{
//parse the information
var age_in_days : Int = (station["age_in_days"] as String).toInt()!
var hight_normal: Double = (station["height_nom"] as NSString).doubleValue
var hight_over : Double = (station["height_ovr"] as NSString).doubleValue
var latitude: CLLocationDegrees = (station["lat"] as NSString).doubleValue
var longitude: CLLocationDegrees = (station["lon"] as NSString).doubleValue
var station_id : Int = (station["station_id"] as String).toInt()!
注意:类型String不包含.toDouble()函数,这就是我不得不使用类型NSString的原因。
另外,非常重要注意:两个键“age_in_days”和“station_id”在JSON中显示为int类型(如上面的引用中所示),但NSJSONSerialization函数从String类型中获取所有值!