ios - Swift 可编码,当 JSON 中缺少键时,类属性的默认值

标签 ios swift xcode swift4 codable

如您所知,Codable 是 swift 4 中的新内容,因此我们将从旧的模型初始化过程转移到这个。通常我们使用以下场景

class LoginModal
{    
    let cashierType: NSNumber
    let status: NSNumber

    init(_ json: JSON)
    {
        let keys = Constants.LoginModal()

        cashierType = json[keys.cashierType].number ?? 0
        status = json[keys.status].number ?? 0
    }
}

JSON 中的 cashierType Key 可能会丢失,因此我们将默认值设为 0

现在使用 Codable 执行此操作非常简单,如下所示

class LoginModal: Coadable
{    
    let cashierType: NSNumber
    let status: NSNumber
}

如上所述,键可能会丢失,但我们不希望模型变量是可选的,那么我们如何使用 Codable 实现这一点。

谢谢

最佳答案

使用 init(from decoder: Decoder) 设置模型中的默认值。

struct LoginModal: Codable {

    let cashierType: Int
    let status: Int

    enum CodingKeys: String, CodingKey {
        case cashierType = "cashierType"
        case status = "status"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
        self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
    }
}

数据读取:

do {
        let data = //JSON Data from API
        let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
        print("\(jsonData.status) \(jsonData.cashierType)")
    } catch let error {
        print(error.localizedDescription)
    }

关于ios - Swift 可编码,当 JSON 中缺少键时,类属性的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53237085/

相关文章:

ios - Xcode 6.4 导出临时 "Session has expired"

ios - 在 SwiftUI 中更改 UIView 背景颜色

ios - 如何从 Objective C 类访问 swift 类的 List 属性

ios - 如何获取_所有_ NSURLRequest 数据?

ios - CGContextDrawImage错误,如何分配缓冲区?

ios - 获取 iPhone 所在的国家(没有 CLLocationManager)

ios - IOS Swift4中AES128解密

c - C 中的宏扩展

用于条形码扫描的 swift Avcapture session 无法正常工作

xcode - 如何在 XCode 中删除断点