为什么JSONDecoder总是为可选属性返回nil?

为什么JSONDecoder总是为可选属性返回nil?,json,swift,urlsession,Json,Swift,Urlsession,我得到一个键,其中可以是nil。因此,我在数据模型中使用了一个可选属性,但是在解码之后,我总是得到该属性的nil,即使在JSON中,value by key包含字符串而不是nil。下面是我得到的响应和到控制台的输出,在控制台中我检查写入profilePath属性的值 响应: {“成人”:false,“性别”:2,“id”:544002,“因大学部而闻名”:“表演”,“姓名”:“朱利奥·贝鲁蒂”,“原名”:“朱利奥·贝鲁蒂”,“人气”:2.467,“简介路径”:“/ktPKniWGVkm6eBG7

我得到一个键,其中可以是
nil
。因此,我在数据模型中使用了一个可选属性,但是在解码之后,我总是得到该属性的
nil
,即使在JSON中,value by key包含字符串而不是
nil
。下面是我得到的响应和到控制台的输出,在控制台中我检查写入
profilePath
属性的值

响应:

{“成人”:false,“性别”:2,“id”:544002,“因大学部而闻名”:“表演”,“姓名”:“朱利奥·贝鲁蒂”,“原名”:“朱利奥·贝鲁蒂”,“人气”:2.467,“简介路径”:“/ktPKniWGVkm6eBG7a2R7WGd96kZ.jpg”,“演员id”:1,“角色”:“加布里埃尔·爱默生”,“信用证”:“5fdad9cfeda4b70041400df3”,“命令”:1},“成人”:false,“性别”:28970,{,“知名部门”:“代理”,“姓名”:“瑞德·惠灵顿”,“原名”:“瑞德·惠灵顿”,“人气”:0.6,“个人资料路径”:空,,“演员id”:2,“角色”:“西蒙·塔尔博特”,“信用id”:“5FDAD9DD3F7E10404042F859”,“订单”:2}

控制台输出:


JSON文件中的属性名是
profile\u path
,但您尝试将其解码为
profilePath
。 您应该添加一个枚举来定义JSON键,如

enum CodingKeys: String, CodingKey {
    case profilePath = "profile_path"
    // add the other keys as well
}

JSON for
profilePath
属性中的键是
profile\u path
。因此,您只需将
JSONDecoder
属性的
keyDecodingStrategy
设置为
。convertFromSnakeCase
即可正确解码:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
    let movies = try JSONDecoder().decode(MovieCreditResponse.self, from: data!)
} catch {
    // Handle error
    print(error)
}

另外,通常使用
try!
是非常糟糕的做法。你应该
尝试捕捉
并处理抛出的错误。

似乎我尝试了这个,错误出现了:
类型“MovieCast”不符合协议“Decodable”
@Heimdallr这也是一个有效的解决方案。你只需要包含所有缺少的正确选项
MovieCast
struct的关系作为
CodingKeys
enum中的案例。
enum CodingKeys: String, CodingKey {
    case profilePath = "profile_path"
    // add the other keys as well
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
    let movies = try JSONDecoder().decode(MovieCreditResponse.self, from: data!)
} catch {
    // Handle error
    print(error)
}