在Swift中解析OpenWeatherMap中的JSON
我与工作有联系,但我无法从天气阵列中获得描述。因为它是数组中的字典在Swift中解析OpenWeatherMap中的JSON,json,swift,parsing,httprequest,openweathermap,Json,Swift,Parsing,Httprequest,Openweathermap,我与工作有联系,但我无法从天气阵列中获得描述。因为它是数组中的字典 {"weather": [{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}]} 获取温度的工作原理如下: if let main = item["main"] as?
{"weather":
[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}]}
获取温度的工作原理如下:
if let main = item["main"] as? NSDictionary {
println("Main existe")
if let temp = main["temp"] {
println("Temp existe")
weatherRequested.append(temp.stringValue)
}
}
iOS中使用Swift的默认JSON解析非常糟糕。我建议您使用
SwiftyJSON
库。这将使解析变得像
let result = JSON(jsonResult)
let weatherDesc = result["weather"]["description"].stringValue
let weatherTemp = result["main"]["temp"].stringValue
希望有帮助 iOS中使用Swift的默认JSON解析显然是错误的。我建议您使用
SwiftyJSON
库。这将使解析变得像
let result = JSON(jsonResult)
let weatherDesc = result["weather"]["description"].stringValue
let weatherTemp = result["main"]["temp"].stringValue
希望有帮助 您在这方面犯了一个错误
if let item = jsonResult[0] as? NSDictionary {
jsonResult是NSDictionary而不是数组。删除“[0]”,然后再试一次中有错误
if let item = jsonResult[0] as? NSDictionary {
jsonResult是NSDictionary而不是数组。删除“[0]”并重试我最终想出了一个解决方案:
if let item = jsonResult as? NSDictionary {
if let weather = item["weather"] as? NSArray{
if let value = weather[0] as? NSDictionary{
if let description = value["description"] as? String{
weatherRequested.append(description)
}
}
}
if let main = item["main"] as? NSDictionary {
if let temp = main["temp"] {
weatherRequested.append(temp.stringValue)
}
}
}
感谢任何试图帮助我的人!:) 我最终想出了一个解决方案:
if let item = jsonResult as? NSDictionary {
if let weather = item["weather"] as? NSArray{
if let value = weather[0] as? NSDictionary{
if let description = value["description"] as? String{
weatherRequested.append(description)
}
}
}
if let main = item["main"] as? NSDictionary {
if let temp = main["temp"] {
weatherRequested.append(temp.stringValue)
}
}
}
感谢任何试图帮助我的人!:) 我读到苹果拒绝应用程序是因为他们不喜欢使用第三方库,所以我试图避免使用这些库,并坚持使用苹果的东西,即使它有点复杂/painfull@PabloDuque:不,我在应用商店中有一个已接受的应用程序,它使用此库和许多其他库!哦,太棒了!!!很抱歉提出这个愚蠢的问题,但是我如何正确导入这样的库呢让我们感谢像Cocoapods这样的依赖管理者。然后,只需将
pod'Alamofire'、“~>3.0”
添加到pod文件并运行pod install
即可。检查一下,我读到苹果拒绝应用程序是因为他们不喜欢使用第三方库,所以我试图避免使用这些库,并坚持使用苹果的东西,即使它有点复杂/painfull@PabloDuque:不,我在应用商店中有一个已接受的应用程序,它使用此库和许多其他库!哦,太棒了!!!很抱歉提出这个愚蠢的问题,但是我如何正确导入这样的库呢让我们感谢像Cocoapods这样的依赖管理者。然后,只需将pod'Alamofire'、“~>3.0”
添加到pod文件并运行pod install
即可。检查您是否将值[“description”]转换为?NSMutableString
,然后再次将其转换为String。这没有意义,你应该直接将它转换为字符串。它不允许我直接从NSDictionary转换为字符串,必须先通过NSMutableString。你应该把value[“description”]
直接转换成as?字符串
,而不是作为?NSMutableString
。这样你就不必在追加中再次施放了。我看错了,我的错。我写的方式很好,但你说的很有道理。我会改变的!好。现在你的答案好多了您正在将值[“description”]转换为?NSMutableString
,然后再次将其转换为String
。这没有意义,你应该直接将它转换为字符串。它不允许我直接从NSDictionary转换为字符串,必须先通过NSMutableString。你应该把value[“description”]
直接转换成as?字符串
,而不是作为?NSMutableString
。这样你就不必在追加中再次施放了。我看错了,我的错。我写的方式很好,但你说的很有道理。我会改变的!好。现在你的答案好多了