Пытаюсь раскрасить данные, чтобы потом выложить в TableView, но ловлю ошибку:
keyNotFound(App.Animals.(CodingKeys in _EBC6E47D2E8ACFFEC4B52F4698C3D2D3).animal, Swift.DecodingError.Context(codingPath: [], debugDescription: “No value associated with key animal (“animal”).”, underlyingError: nil))
Вот мой код:
func getAnimal() {
guard let url = URL(string: "http://test.com/rest/animal") else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accepts")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] else {return}
print("(\n\n\n\n\n\(json)")
let decoder = JSONDecoder()
let downloadedAnimals = try decoder.decode(Animals.self, from: data)
self.animals = downloadedAnimals.animal
print("my animal = \(self.animals)")
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
class Animals: Codable {
let animal: [Animal]
init(animal: [Animal]) {
self.animal = animal
}
}
class Animal: Codable {
let animalName: [String]
let animalAbout: [String]
init(animal_title: [String], animal_about: [String]){
self.animalName = animal_title
self.animalAbout = animal_about
}
private enum CodingKeys: String, CodingKey {
case animalName = "animal_title"
case animalAbout = "animal_about"
}
}
Получаемый JSON выглядит следующим образом:
{«animals":[{"animal":{"animal_title":"hiking","animal_color":"Red","animal_birthdate":"02.04.2018","animal_image":{"src":"http:\/\/test.com\/sites\/default\/files\/IMG_20180322_175407_771.txt","alt":""},"animal_about":"bulb "}},{"animal":{"animal_title":"Random animal","animal_color":"Purple","dino_birthdate":"09.05.2005","dino_image":{"src":"http:\/\/dinotest.art-coral.com\/sites\/default\/files\/Free-shipping-Inflatable-Dinosaur-Costume-Fan-Operated-Adult-Kids-Size-Halloween-Cosplay-Animal-Dino-Rider-T_6.jpg","alt":""},"dino_about":"People's best friend"}},
{"dino":{"dino_title":"Terri","dino_color":"Green","dino_birthdate":"06.04.1988","dino_image":{"src":"http:\/\/dinotest.art-coral.com\/sites\/default\/files\/1-pihskuyxeeulvjfbwhjnlg.jpeg","alt":""},"dino_about":"Dinosaurs belong to a group known as archosaurs, which also includes modern crocodilians. Within the archosaur group, dinosaurs are differentiated most noticeably by their gait. Dinosaur legs extend directly beneath the body, whereas the legs of lizards and crocodilians sprawl out to either side."}}]}