ios - Swift - 可选属性的 JSON 序列化
问题描述
我有一个从 JSON(序列化)创建的对象。这个对象有一个可选的属性。当此可选属性为空时,服务器不会在负载中发送该属性的密钥。处理这些类型的场景(关于错误处理)的正确方法是什么?
imageURL
是可选的。这意味着有时profileImgPath
JSON 中不存在
import UIKit
class Person: Codable {
let firstName: String
let lastName: String
let imageURL: URL?
let id: String
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
case imageURL = "profileImgPath"
case id = "_id"
}
init(id: String, firstName: String, lastName: String, imageURL:URL) {
self.id = id
self.firstName = firstName
self.lastName = lastName
self.imageURL = imageURL
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.id = try values.decode(String.self, forKey: .id)
self.firstName = try values.decode(String.self, forKey: .firstName)
self.lastName = try values.decode(String.self, forKey: .lastName)
self.imageURL = try? values.decode(URL.self, forKey: .imageURL)
}
}
struct PersonsList : Codable {
let persons: [Person]
}
序列化
let jsonData = try JSONSerialization.data(withJSONObject: JSON, options: [])
let decoder = JSONDecoder()
let patientList = try! decoder.decode(PatientsList.self, from: jsonData)
我收到此错误:
线程 1:致命错误:“尝试!” 表达式意外引发错误: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "profileImgPath", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "patients", intValue: nil), _JSONKey(stringValue : "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"profileImgPath\", intValue: nil) (\"profileImgPath\").", underlyingError: nil))
解决方案
这很容易。
使用 decodeIfPresent
self.imageURL = try values.decodeIfPresent(String.self, forKey: . imageURL)
推荐阅读
- sql - 需要在 WHERE/HAVING 中使用 COUNT 来返回打开和关闭
- python - python中大型数据集的反向消除
- curl - 使用 curl 将新事件插入 CalDAV 日历
- react-native - React Native Maps 不会在 iOS 上重新渲染标记
- wso2 - WSO2 API Manager 正文中的两个参数
- python - 使用 Python Spark 从 Hadoop 表中提取 Json 对象的所有键
- javascript - 按键对 Javascript 对象进行排序
- python - rpy2在python中加载R-dataframe会产生错误的时间戳
- r - 处理使用 Haven 导入的标记变量的最佳方法是什么?
- ios - 是否可以在 Flutter 中更改 CupertinoTabBar 的高度?