Swift-可选属性的JSON序列化

时间:2018-06-29 18:22:55

标签: ios json swift serialization

我有一个从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:无),   Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:   “患者”,intValue:无),_JSONKey(stringValue:“索引0”,intValue:   0)],debugDescription:“没有与键关联的值   CodingKeys(stringValue:\“ profileImgPath \”,intValue:无)   (\“ profileImgPath \”)。“,underlyingError:nil))

1 个答案:

答案 0 :(得分:2)

那很容易。

使用decodeIfPresent

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