【问题标题】:Swift - JSON Serialisation of an optional propertySwift - 可选属性的 JSON 序列化
【发布时间】:2018-12-08 23:39:58
【问题描述】:

我有一个从 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(编码键(字符串值: "profileImgPath", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "患者", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "没有与键关联的值 CodingKeys(stringValue: \"profileImgPath\", intValue: nil) (\"profileImgPath\").",基础错误:nil))

【问题讨论】:

  • 1.将Person 设为struct,然后您可以删除这两个init 函数。 2. 如果imageURL 是可选的,则将其设为可选。 let imageURL: URL?。 3.使Person符合Codable
  • @rmaddy Person 是一个超类,有 2 个子类。结构不能有继承。
  • 好的,然后忽略我的第一点。其他两个仍然适用。
  • 只需将此属性设为可选let imageURL: URL?
  • @rmaddy 我已经根据您的建议更新了我的问题和代码。但我仍然收到错误(也添加了它)

标签: ios json swift serialization


【解决方案1】:

这很容易。

使用 decodeIfPresent

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

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多