简体   繁体   English

当JSON中缺少键时,Swift可编码,默认值为Class属性

[英]Swift codable, Default Value to Class property when key missing in the JSON

As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. 如你所知,Codable是swift 4中的新东西,所以我们将从模型的旧的初始化过程转向这个。 Usually we use the following Scenario 通常我们使用以下场景

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
    }
}

In the JSON cashierType Key may missing, so we giving the default Value as 0 在JSON中, cashierType Key可能会丢失,因此我们将默认值设为0

Now while doing this with Codable is quite easy, as following 现在,使用Codable执行此操作非常简单,如下所示

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

as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable. 如上所述,键可能会丢失,但我们不希望模型变量是可选的,那么我们如何使用Codable实现这一点。

Thanks 谢谢

Use init(from decoder: Decoder) to set the default values in your model. 使用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
    }
}

Data Reading: 资料阅读:

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)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM