I am trying to get response values from an API url using Alamofire. I created a data model and the response is fine but I am getting null for poster_path and release_date. I was wondering how can handle JSON response correctly. here is my code:
let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
func fetchMovies( completion: @escaping(MovieResponse?, AFError?) -> Void) {
let url = URL(string: "url")!
let params = [:]
AF.request(url, method: .get , parameters: params)
.responseDecodable(of: Data.self, decoder: decoder) { response in
switch response.result {
case .success(let movies):
completion(movies, nil)
case .failure(let error):
completion(nil , error)
}
}
}
Response:
JSON example:
"results": [
{
"adult": false,
"backdrop_path": "/5hNcsnMkwU2LknLoru73c76el3z.jpg",
"genre_ids": [
35,
18,
10749
],
"id": 19404,
"original_language": "hi",
"original_title": "दिलवाले दुल्हनिया ले जायेंगे",
"overview": "Raj is a rich, carefree, happy-go-lucky second generation NRI. Simran is the daughter of Chaudhary Baldev Singh, who in spite of being an NRI is very strict about adherence to Indian values. Simran has left for India to be married to her childhood fiancé. Raj leaves for India with a mission at his hands, to claim his lady love under the noses of her whole family. Thus begins a saga.",
"popularity": 27.119,
"poster_path": "/2CAL2433ZeIihfX1Hb2139CX0pW.jpg",
"release_date": "1995-10-20",
"title": "Dilwale Dulhania Le Jayenge",
"video": false,
"vote_average": 8.7,
"vote_count": 3275
},
>Solution :
Remove the entire CodingKeys enum in Movie.
The convertFromSnakeCase strategy does already the key mapping.
And don’t declare all properties carelessly as optional. Serious services like themoviedb send very consistent data. At least most likely a movie has always a title and an identifier.
