【问题标题】:JSONDecoder() deal with Null values only in SwiftJSONDecoder() 仅在 Swift 中处理 Null 值
【发布时间】:2020-04-25 14:10:55
【问题描述】:

这是我的 JSON 响应。

结构:

struct Welcome: Codable {
    let name: String
    let id: Int
}

JSON:

{
    "name": "Apple",
    "id": 23
}

这是 JSON 的结构,但名称有时会为空。所以,我想用默认字符串值而不是 null 替换。因为为了避免将来应用崩溃。

{
    "name": null,
    "id": 23
}

如果名称为 null,那么我只想为属性 name 提供默认值,例如“orange”。我不想对id 做任何事情。

我提到一些 SO 答案令人困惑,并且使用 init 中的所有属性而不是选定属性。这对我来说是不可能的,因为我有 200 个 JSON 属性,其中 50 种类型将是 null 或将具有值..

我该怎么做?提前致谢。

【问题讨论】:

  • 您可能希望在所需属性周围添加一个包装器。

标签: json swift swift3 jsondecoder


【解决方案1】:

您可以(在某种程度上)通过制作包装器来实现:

struct Welcome: Codable {
    private let name: String? // <- This should be optional, otherwise it will fail decoding
    var defaultedName: String { name ?? "Orange" }

    let id: Int
}

这也将确保服务器永远不会获得default 值。

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2016-07-06
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多