SWIFT:尝试解码JSON,返回nil

问题描述

当我尝试调用.decode()解码结构时,它返回nil。有人可以帮助我吗?

我的应用从这行代码的JSON数据中返回空值:

   let newPosData = try JSONDecoder().decode(NewPosDataBase.self,from: responseData)

以下是完整的代码

func getNewLFNREXT(invnr: String,completionHandler: @escaping (String,Bool,NewPosDataBase?) -> Void) {
        let headers: HTTPHeaders = [
            .authorization(username: UserCredentials.shared.username,password: UserCredentials.shared.password),.accept("application/json")
        ]
        
        let url:String = Config.middleware + Config.url + "/mobile/lfnrext?invnr=\(invnr)"
        AF.request(url,method: .get,parameters: [:],headers: headers).responseJSON { response in
            if response.response?.statusCode == 200 {
                
                do {
                    guard let responseData = response.data else {
                        completionHandler(errorMessage,false,nil )
                        return
                    }
                    
                    let newPosData = try JSONDecoder().decode(NewPosDataBase.self,from: responseData)
                    
                    print( newPosData.newPosData?.newLfnrext)
                    completionHandler("",true,newPosData)
                    
                } catch {
                    completionHandler(errorMessage,nil )
                }
                
            }else {
                let message = self.getErrorMessageFrom(data: response.data,defaultErrorMessage: errorKeineDaten)
                completionHandler(message,nil)
            }
        }
        
    }

解决方法

如果键名不同于enum CodingKeys类型的属性名,则需要添加 Codable

因此,您的模型应该像

class NewPosDataBase: Codable {
    enum CodingKeys: String,CodingKey {
        case newPosData = "NEW_POS_DATA"
    }
    //rest of the code...
}

class NewPosData: Codable {
    enum CodingKeys: String,CodingKey {
        case newLfnrext = "NEW_LFNREXT"
        case aktuellerZahler = "AKTUELLER_ZAHLER"
        case gpsStd = "GPS_STD"
    }
    //rest of the code...
}

注意:除非您出于特定目的需要它们,否则无需在模型中提供任何init实现。