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(来自解码器:解码器)设置模型中的默认值.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 – 当JSON中缺少键时,Swift可编码,默认值为Class属性全部内容,希望文章能够帮你解决ios – 当JSON中缺少键时,Swift可编码,默认值为Class属性所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)