gpt4 book ai didi

ios - 如何从 iOS Swift Codable 中的 API 响应通知或打印模型类上缺少的键?

转载 作者:搜寻专家 更新时间:2023-10-30 22:36:28 26 4
gpt4 key购买 nike

我有一个来自 API 的 JSON 响应,如下所示,

上一个 JSON 响应:

[
{
"EmployeeId": 711,
"FirstName": "Steve",
"LastName": "Jobs"
},
{
"EmployeeId": 714,
"FirstName": "John",
"LastName": "Doe"
}
]

和相同的模型类具有以下代码

class EmployeeModel: Codable {

let EmployeeId: Int?
let FirstName: String?
let LastName: String?
}

用于使用 Swift Codable 进行解析

do {
let decodedResponse = try JSONDecoder().decode([EmployeeModel].self, from: response.rawData())
print(decodedResponse)

} catch let jsonErr {
print(jsonErr.localizedDescription)
}

但是现在

最新的 JSON 响应

from API 已更改,并添加了一个 MiddleName 键作为响应,请参见以下屏幕截图,它也可以与 Swift Codable 代码一起正常工作。 enter image description here

但是,在 iOS Swift 5 中,我如何获得通知或打印 MiddleName 键现在已添加到来自 API 的 JSON 响应中?

UPDATE TO QUESTION

根据@CZ54 在下面提供的答案,解决方案工作正常,但它无法检查另一个派生类是否缺少 key 。例如:

enter image description here

// MARK:- LoginModel
class LoginModel: Codable {

let token: String?
let currentUser: CurrentUser?
}

// MARK:- CurrentUser
class CurrentUser: Codable {

let UserName: String?
let EmployeeId: Int?
let EmployeeName: String?
let CompanyName: String?
}

最佳答案

您可以执行以下操作:

let json = """
{
"name" : "Jobs",
"middleName" : "Bob"
}
"""


class User: Decodable {
let name: String
}
extension JSONDecoder {
func decodeAndCheck<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable {
let result = try self.decode(type, from: data)

if let json = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String: Any] {
let mirror = Mirror(reflecting: result)
let jsonKeys = json.map { return $0.0 }
let objectKeys = mirror.children.enumerated().map { $0.element.label }

jsonKeys.forEach { (jsonKey) in
if !objectKeys.contains(jsonKey) {
print("\(jsonKey) is not used yet")
}
}
}
return result

}
}

试试 JSONDecoder().decodeAndCheck(User.self, from: json.data(using: .utf8)!)

//将打印“middleName is not use yet”

关于ios - 如何从 iOS Swift Codable 中的 API 响应通知或打印模型类上缺少的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57490023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com