Home > Back-end >  Getting null value from API response with Alamofire
Getting null value from API response with Alamofire

Time:12-16

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:

enter image description here

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
        },

CodePudding user response:

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.

CodePudding user response:

The keyDecodingStrategy of JSONDecoder default value is .useDefaultKeys

The dateDecodingStrategy of JSONDecoder 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 of posterPath is poster_path

so the keyDecodingStrategy of JSONDecoder, 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:

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
  • Related