gpt4 book ai didi

ios - Swift - 可选属性的 JSON 序列化

转载 作者:搜寻专家 更新时间:2023-11-01 07:01:16 30 4
gpt4 key购买 nike

我有一个从 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)

我收到这个错误:

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: 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)

关于ios - Swift - 可选属性的 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107449/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com