gpt4 book ai didi

ios - 使用 Swift 解析 Json

转载 作者:可可西里 更新时间:2023-11-01 01:44:11 25 4
gpt4 key购买 nike

我正在尝试新的 iOS 语言,但我遇到了问题。我将解析如下 JSON:

{
"coord":{
"lon":-0.13,
"lat":51.51
},
"sys":{
"message":0.1947,
"country":"GB",
"sunrise":1404964557,
"sunset":1405023356
},
"weather":[
{
"id":501,
"main":"Rain",
"description":"moderate rain",
"icon":"10d"
}
],
"base":"cmc stations",
"main":{
"temp":291.87,
"pressure":1018,
"humidity":87,
"temp_min":287.15,
"temp_max":295.45
},
"wind":{
"speed":3.1,
"deg":350,
"var_beg":320,
"var_end":30
},
"rain":{
"3h":0.5
},
"clouds":{
"all":75
},
"dt":1404999902,
"id":2643743,
"name":"London",
"cod":200
}

我从天气预报服务中获取了JSON,直到现在我做了以下方法:

func getWeatherFinished(json:NSDictionary) {
if (json != nil) {
var weather: NSArray = json.objectForKey("weather") as NSArray
var weatherDict: NSDictionary = weather.objectAtIndex(0) as NSDictionary
var weatherConditions: NSString = weatherDict.objectForKey("description") as NSString

var mainDict: NSDictionary = json.objectForKey("main") as NSDictionary
var temp: NSString = mainDict.objectForKey("temp") as NSString
var humidity: NSString = mainDict.objectForKey("humidity") as NSString
var minTemp: NSString = mainDict.objectForKey("temp_min") as NSString
var maxTemp: NSString = mainDict.objectForKey("temp_max") as NSString

var windDict: NSDictionary = json.objectForKey("wind") as NSDictionary
var speed: NSString = windDict.objectForKey("speed") as NSString
var deg: NSString = windDict.objectForKey("deg") as NSString
}
}

但是当我运行该应用程序时它崩溃了,我不知道为什么。我的代码有什么问题?为什么会崩溃?

错误截图: enter image description here

当我得到 JSON 时,我写了这段代码:

    func connectionDidFinishLoading(connection: NSURLConnection!) {

var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions(1), error: nil)
if let jsonDict = json as? NSDictionary {
getWeatherFinished(json as NSDictionary)
}

}

最佳答案

尝试检查以确保您的 JSON 不是 nil 并且可以是字典:

func connectionDidFinishLoading(connection: NSURLConnection!) {
var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions(1), error: nil)
if let jsonDict = json as? NSDictionary{
getWeatherFinished(json)
}

}

这一行会崩溃,因为带有键“temp”的对象不是 NSString。

var temp: NSString = mainDict.objectForKey("temp") as NSString

从你的 json 来看,它看起来像是一个数字,所以你可以试试这个:

var tempNum: NSNumber = mainDict.objectForKey("temp") as NSNumber
var temp: NSString = tempNum.stringValue()

关于ios - 使用 Swift 解析 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24678400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com