JSONDecoder() 仅处理 Swift 中的 Null 值

JSONDecoder() deal with Null values only in Swift

这是我收到的 JSON 回复。

结构:

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

JSON:

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

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

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

如果名称为空,那么我只想为 属性 name 提供默认值,如“orange”。我不想对 id.

做任何事情

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

我该怎么做?提前致谢。

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

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 值。