【问题标题】:How to convert JSON into [WeatherModel] in Swift/SwiftyJSON?如何在 Swift/SwiftyJSON 中将 JSON 转换为 [WeatherModel]?
【发布时间】:2023-03-10 07:38:02
【问题描述】:

我正在尝试制作一个天气应用程序。并且在使用 SwiftyJSON 时遇到问题。 我需要将 [WeatherModel] 分配给我的 JSON 数据。 基本上,我需要将 json 变量设置为 weatherData。代码如下。

这是我的控制器:

var weatherData = [WeatherModel]()

func getJSONData(completed: @escaping () -> ()) {
    if let filepath = Bundle.main.path(forResource: "weather", ofType: "json") {
            do{
                let data = try Data(contentsOf: URL(fileURLWithPath: filepath), options: .alwaysMapped)
                let json = JSON(data: data)
                // And here I need to set json to weatherData

            } catch let error{
                print(error.localizedDescription)
            }

            DispatchQueue.main.async {
                completed()
            }
    } else {
        print("file not found")
    }
}

这是我的 WeatherModel 结构:

struct WeatherModel {
  let cod: String
  let message: Double
  let cnt: Int
  let list: [List]
  let city: City
}

注意:我真的需要只使用 SwiftJSON 来制作它。任何帮助将不胜感激:]

【问题讨论】:

  • 为什么要使用第三方库?只需使用内置的DecodableJSONDecoder
  • @rmaddy,因为实现起来很简单,而且(恕我直言)JSONDecoder 与 SwiftyJSON 相比是一团糟。
  • 如果您从捆绑包中加载数据,天气将永远不会改变????。 @LinusGeffarth 请重新考虑您的意见。如果您不知道自己在做什么,SwiftyJSON 可能是一个不错的选择。否则Codable 会更强大。
  • @vadian,这就是我要说的。 Codable 真的很整洁。但是为了一个简单的开始,SwiftyJSON 绝对是一个很好的方法。
  • 你留下了很多松散的结局。请提供您希望收到的 JSON 示例。请提供您的 List 结构以完成您的 Model 期望。请提供一些的想法,说明你想在completed 闭包中做什么,以及如果没有传递给你的处理程序,你想如何访问你的weatherData。与简单地将一些(未知)JSON 转换为 [WeatherModel] 相比,您的代码似乎存在更多问题。

标签: json swift swift4


【解决方案1】:

好吧,我们不知道您的 JSON 是什么样的。
提供一个示例,如果您的 JSON 是这样的:

{
  "data": [
    {
      "cod": "some string here",
      "message": 2.0,
      "cnt": 1
      ...
    }
  ]
}

...您将按如下方式对其进行解码:

for (_, dict) in json["data"] {
    guard let cod = dict["cod"].string else { continue }
    guard let message = dict["message"].double else { continue }
    guard let cnt = dict["cnt"].int else { continue }
    // ...
    let weather = WeatherModel(cod: cod, message: message, cnt: cnt, ...)
    weatherData.append(weather)
}

您必须修改它以使用您的 json 格式和确切的要求。

【讨论】:

  • 谢谢,我稍后再试,如果有什么事情会告诉你
【解决方案2】:

试试这个,我不确定你的 json 结构是否正确。

struct WeatherModel:Codable {

    let cod: String
    let message: Double
    let cnt: Int
    let list: [List]
    let city: City

    enum CodingKeys: String, CodingKey
    {
       case title = "name"
       case url = "message"
       case cnt
       case list
      case city
    }

}

struct City:Codable {

    let name
}
struct List:Codable {

    //define your list data as in json
}

在此解码您的 json 数据之后。

if let wheatherData = try? JSONDecoder().decode(WeatherModel.self, from: data) {
 // here Is your json model weatherData
}

【讨论】:

  • 是的,基本上我是在使用Codable 解析 JSON。但现在,它应该只使用 SwiftyJSON。
猜你喜欢
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多