【问题标题】:Parsing JSON from OpenWeatherMap in Swift在 Swift 中从 OpenWeatherMap 解析 JSON
【发布时间】:2016-02-29 14:53:58
【问题描述】:

我已经建立了连接,但 我无法从天气数组中获取描述。因为它是一个数组内的字典

{"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)
            }
        }

【问题讨论】:

    标签: json swift parsing httprequest openweathermap


    【解决方案1】:

    我最终想出了一个解决方案:

     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)
                }
            }
        }
    

    感谢任何试图帮助我的人! :)

    【讨论】:

    • 您正在投射 value["description"] as? NSMutableString,然后再次投射 as String。没有意义,你应该直接把它转换成String。
    • 它没有让我直接从 NSDictionary 转换为 String,必须先通过 NSMutableString。它工作得很好。
    • 你应该直接投射value["description"] as? String,而不是as? NSMutableString。这样您就不必在append 中再次投射。
    • 我读错了,我的错。它按照我写的方式工作得很好,但是你所说的很有意义。我会做出改变的!
    • 好。现在你的答案好多了。 :)
    【解决方案2】:

    你有一个错误

    if let item = jsonResult[0] as? NSDictionary {
    

    jsonResult 是一个 NSDictionary 而不是一个数组。删除“[0]”并重试

    【讨论】:

      【解决方案3】:

      iOS 中使用 Swift 的默认 JSON 解析非常糟糕。我建议您使用SwiftyJSON 库。这将使解析它变得像...一样简单。

      let result = JSON(jsonResult)
      let weatherDesc = result["weather"]["description"].stringValue
      let weatherTemp = result["main"]["temp"].stringValue
      

      希望有帮助!

      【讨论】:

      • 我读到苹果拒绝了应用程序,因为他们不喜欢使用第三方库,所以我试图避免使用这些库并坚持使用苹果的东西,即使它有点复杂/痛苦的
      • @PabloDuque:不,我在 App Store 上有一个接受的应用程序,它使用这个库和许多其他库!
      • 哦,太好了!!!抱歉这个愚蠢的问题,但我如何正确导入这样的库? :S 谢谢
      • 使用像 Cocoapods 这样的依赖管理器。然后就像将pod 'Alamofire', '~> 3.0' 添加到您的Podfile 并运行pod install 一样简单。检查cocoapods.org
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多