微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift4 – 使用Codable将收到的Int转换为Bool解码JSON

我有这样的结构:
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但会找到一个号码.”

我的建议是:不要打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现在没有等价.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐