私はこのような構造を持っています:
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 をデコードすると予想されますが、代わりに数字が見つかりました。」というエラーが表示されます。