如何在Swift / SwiftyJSON中将JSON转换为[WeatherModel]?

时间:2018-06-10 21:09:20

标签: json swift swift4

我正在尝试制作天气应用。并且使用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。任何帮助将不胜感激:]

2 个答案:

答案 0 :(得分:0)

好吧,我们不知道您的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格式和确切的要求。

答案 1 :(得分:0)

试试这个,我不确定你的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
}