在使用 JSONDecoder().decode in Swift 解码 API 响应后,自定义数据模型中的字段为 "nil" 5
Fields in custom data model are "nil" after decoding API response with JSONDecoder().decode in Swift 5
我在 Swift 中为用户对象定义了自定义数据模型,如下所示:
user data model
我有一个函数可以从 API 中提取用户数据,如下所示:
get data from api
这是使用 Postman 调用相同端点时的响应:
api response
这是我函数第 75 行的控制台调试输出,显示我实际上正在接收该数据:debug output
据我所知,一切看起来都不错。
然后我使用 JSONDecoder().decode 解码我从 api 收到的 jsonData,我没有收到任何错误。但是,当我从返回的用户对象中打印一个字段时,该字段(以及所有其他字段)是 "nil": all fields in user object are nil
我确定它是一些小而愚蠢的东西,但我现在已经花了好几个小时,但无法弄清楚它是什么。任何人都可以发现错误并让我知道我在这里做错了什么吗?
不胜感激!!!
对于 Codable,您需要为 json 键提供相同的属性名称。并确保它在正确的范围内。例如,您在 detailresponse json 对象和 detailresponse 主对象 json 内部发送电子邮件属性。如果你不想更多 class 你需要使用它的 init 容器方法。
class Response: Codable {
var statuscode: Int?
var response_type: Int?
// Other properties
var detailresponse: DetailResponse?
}
class DetailResponse: Codable {
var id: Int?
// Other properties
var socialmediadata: User?
}
class User: Codable {
var id: Int?
var email: String?
// Other properties
}
现在,json 将像这样解析。
let response = try JSONDecoder().decode(Response.self, from: jsonData)
print(response.detailresponse?.socialmediadata?.email ?? "")
我在 Swift 中为用户对象定义了自定义数据模型,如下所示: user data model
我有一个函数可以从 API 中提取用户数据,如下所示: get data from api
这是使用 Postman 调用相同端点时的响应: api response
这是我函数第 75 行的控制台调试输出,显示我实际上正在接收该数据:debug output
据我所知,一切看起来都不错。 然后我使用 JSONDecoder().decode 解码我从 api 收到的 jsonData,我没有收到任何错误。但是,当我从返回的用户对象中打印一个字段时,该字段(以及所有其他字段)是 "nil": all fields in user object are nil
我确定它是一些小而愚蠢的东西,但我现在已经花了好几个小时,但无法弄清楚它是什么。任何人都可以发现错误并让我知道我在这里做错了什么吗?
不胜感激!!!
对于 Codable,您需要为 json 键提供相同的属性名称。并确保它在正确的范围内。例如,您在 detailresponse json 对象和 detailresponse 主对象 json 内部发送电子邮件属性。如果你不想更多 class 你需要使用它的 init 容器方法。
class Response: Codable {
var statuscode: Int?
var response_type: Int?
// Other properties
var detailresponse: DetailResponse?
}
class DetailResponse: Codable {
var id: Int?
// Other properties
var socialmediadata: User?
}
class User: Codable {
var id: Int?
var email: String?
// Other properties
}
现在,json 将像这样解析。
let response = try JSONDecoder().decode(Response.self, from: jsonData)
print(response.detailresponse?.socialmediadata?.email ?? "")