Как преобразовать JSON в [WeatherModel] в Swift / SwiftyJSON? - PullRequest
0 голосов
/ 11 июня 2018

Я пытался сделать приложение погоды.И возникли проблемы с использованием 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 голосов
/ 11 июня 2018

Попробуйте, я не уверен в правильности вашей структуры 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
}
0 голосов
/ 11 июня 2018

Ну, мы не знаем, как выглядит ваш 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 и точными требованиями.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...