我有这样的结构:
struct JSONModelSettings {
let patientID : String
let therapistID : String
var isEnabled : Bool
enum CodingKeys: String, CodingKey {
case settings // The top level "settings" key
}
// The keys inside of the "settings" object
enum SettingsKeys: String, CodingKey {
case patientID = "patient_id"
case therapistID = "therapist_id"
case isEnabled = "is_therapy_forced"
}
}
extension JSONModelSettings: Decodable {
init(from decoder: Decoder) throws {
// Extract the top-level values ("settings")
let values = try decoder.container(keyedBy: CodingKeys.self)
// Extract the settings object as a nested container
let user = try values.nestedContainer(keyedBy: SettingsKeys.self, forKey: .settings)
// Extract each property from the nested container
patientID = try user.decode(String.self, forKey: .patientID)
therapistID = try user.decode(String.self, forKey: .therapistID)
isEnabled = try user.decode(Bool.self, forKey: .isEnabled)
}
}
和这种格式的 JSON(用于在没有额外包装的情况下从设置中提取键的结构):
{
"settings": {
"patient_id": "80864898",
"therapist_id": "78920",
"enabled": "1"
}
}
问题是我如何将“isEnabled”转换为 Bool,(从 API 获取 1 或 0)当我尝试解析响应时,我得到错误:“预期解码 Bool,但找到了一个数字。”