Как назначить [WeatherModel] () для типа JSON в Swift? - PullRequest
0 голосов
/ 09 июня 2018

Я строил модель для моего объекта JSON.И я это сделал.Теперь я должен объявить переменную для него в ViewController и назначить его моему объекту json.Любая помощь будет оценена.

Вот как я анализирую json из файла и объявляю переменную:

 var weatherData = [WeatherModel]()

 func getJSONData(completed: @escaping () -> ()) {
    if let filepath = Bundle.main.path(forResource: "weather", ofType: "json") {
        if let data = try? String(contentsOf: URL(fileURLWithPath: filepath)) {
            let json = JSON(parseJSON: data)

            // I must assign json to weatherData here

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

Вот моя модель jus на случай:

struct WeatherModel: Codable {
  let list: [List]
  let city: City
}

struct City: Codable {
  let name: String
}

struct List: Codable {
  let main: Main
  let weather: [Weather]
  let dtTxt: String

  enum CodingKeys: String, CodingKey {
    case main, weather
    case dtTxt = "dt_txt"
  }
}

 struct Main: Codable {
    let temp: Double
 }

 struct Weather: Codable {
    let main, description: String
 } 

РЕДАКТИРОВАТЬ: Вот погода.json

     {
       "list": [
        {
           "main": {
               "temp": 277.12
            },
        "weather": [{
            "main": "Clouds",
            "description": "scattered clouds"
        }],
        "dt_txt": "2018-06-05 15:00:00"
    }
],
"city": {
    "name": "Bishkek"
   }
  }

Примечание: если в моем коде есть какие-либо ошибки, рад услышать решение.

1 Ответ

0 голосов
/ 09 июня 2018

Вместо:

let json = JSON(parseJSON: data)

Вы должны использовать JSONDecoder

let weatherData = try JSONDecoder().decode([WeatherModel].self,
                                           from:data)

В примере:

if let filepath = Bundle.main.path(forResource: "weather", ofType: "json") {
    do {
        let data = try Data(contentsOf: URL(fileURLWithPath: filepath))

        weatherData = try JSONDecoder().decode([WeatherModel].self,
                                               from:data)
        print(weatherData)
    }
    catch {
        print(error)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...