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
},
2
Answers
The
keyDecodingStrategy
ofJSONDecoder
default value is.useDefaultKeys
The
dateDecodingStrategy
ofJSONDecoder
default value is.deferredToDate
ps:
The
.deferredToDate
format is Apple’s own date format, and it tracks the number of seconds and milliseconds since January 1st 2001. This isn’t really useful.as your write, the
CodingKey
ofposterPath
isposter_path
so the
keyDecodingStrategy
ofJSONDecoder
, you should don’t specify.convertFromSnakeCase
.Leave it to the default value.
For the date value in JSON, you should write your own formatter
so the JSONDecoder should be:
Remove the entire
CodingKeys
enum inMovie
.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.