簡體   English   中英

使用 Alamofire 從 API 響應中獲取 null 值

[英]Getting null value from API response with Alamofire

我正在嘗試使用 Alamofire 從 API url 獲取響應值。 我創建了一個數據 model 並且響應很好,但是我得到了 null 的poster_pathrelease_date 我想知道如何正確處理 JSON 響應。 這是我的代碼:

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

       }

    }

回復:

在此處輸入圖像描述

JSON 示例:

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

keyDecodingStrategyJSONDecoder默認值為.useDefaultKeys

dateDecodingStrategyJSONDecoder默認值為.deferredToDate

ps:

.deferredToDate格式是 Apple 自己的日期格式,它跟蹤自 2001 年 1 月 1 日以來的秒數和毫秒數。這並不是很有用。

正如您所寫, CodingKeyposterPathposter_path

所以keyDecodingStrategyJSONDecoder ,你不應該指定.convertFromSnakeCase

將其保留為默認值。

對於 JSON 中的日期值,您應該編寫自己的格式化程序

所以 JSONDecoder 應該是:

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

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

刪除Movie中的整個CodingKeys枚舉。

convertFromSnakeCase策略已經完成了鍵映射。

並且不要隨意將所有屬性聲明為可選。 themoviedb這樣的嚴肅服務會發送非常一致的數據。 至少很可能一部電影總是有一個標題和一個標識符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM