首页 > 解决方案 > Swift - 可选属性的 JSON 序列化

问题描述

我有一个从 JSON(序列化)创建的对象。这个对象有一个可选的属性。当此可选属性为空时,服务器不会在负载中发送该属性的密钥。处理这些类型的场景(关于错误处理)的正确方法是什么?

imageURL是可选的。这意味着有时profileImgPathJSON 中不存在

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

标签: iosjsonswiftserialization

解决方案


这很容易。

使用 decodeIfPresent

self.imageURL = try values.decodeIfPresent(String.self, forKey: . imageURL)

推荐阅读