JSON中缺少键时,Swift可编码,默认值为Class属性 [英] Swift codable, Default Value to Class property when key missing in the JSON

查看:69
本文介绍了JSON中缺少键时,Swift可编码,默认值为Class属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您所知,Codable是Swift 4中的新功能,因此我们将从模型的较早初始化过程转向这一点。通常我们使用以下场景

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

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

In the JSON cashierType Key may missing, so we giving the default Value as 0

现在使用Codable进行操作非常容易,如下所示

Now while doing this with Codable is quite easy, as following

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

键可能会丢失,但是我们不希望Model Variables是可选的,所以我们可以使用Codable来实现。

as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.

谢谢

推荐答案

使用 init(来自解码器:解码器)设置模型中的默认值。

Use init(from decoder: Decoder) to set the default values in your model.

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

这篇关于JSON中缺少键时,Swift可编码,默认值为Class属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆