swift4 – 使用Codable将收到的Int转换为Bool解码JSON
发布时间:2020-12-14 02:25:44 所属栏目:百科 来源:网络整理
导读:我有这样的结构: 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" objec
|
我有这样的结构:
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)
我的建议是:不要打JSON.尽可能快地将它变成一个Swift值,然后在那里进行操作.
您可以定义一个私有内部结构来保存解码数据,如下所示: struct JSONModelSettings {
let patientID : String
let therapistID : String
var isEnabled : Bool
}
extension JSONModelSettings: Decodable {
// This struct stays very close to the JSON model,to the point
// of using snake_case for its properties. Since it's private,// outside code cannot access it (and no need to either)
private struct JSONSettings: Decodable {
var patient_id: String
var therapist_id: String
var enabled: String
}
private enum CodingKeys: String,CodingKey {
case settings
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let settings = try container.decode(JSONSettings.self,forKey: .settings)
patientID = settings.patient_id
therapistID = settings.therapist_id
isEnabled = settings.enabled == "1" ? true : false
}
}
其他JSON映射框架(例如ObjectMapper)允许您将转换函数附加到编码/解码过程.看起来Codable现在没有等价. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
