Swift Codable 空值处理

Swift Codable null handling

我有一个使用 Codable.

解析 JSON 的结构
struct Student: Codable {
    let name: String?
    let amount: Double?
    let adress: String?
}

现在,如果金额值为 null,则 JSON 解析失败。

那么我是否应该手动处理 Student 结构中存在的所有 IntDouble 的空情况?

作为 null 出现的 String 值被自动处理。

让我为你做这个游乐场,因为一个例子向你展示了一百多个字:

import Cocoa

struct Student: Codable {
    let name: String?
    let amount: Double?
    let adress: String?
}

let okData = """
{
   "name": "here",
 "amount": 100.0,
 "adress": "woodpecker avenue 1"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let okStudent = try decoder.decode(Student.self, from:okData)
print(okStudent)

let nullData = """
{
   "name": "there",
 "amount": null,
"adress": "grassland 2"
}
""".data(using: .utf8)!

let nullStudent = try decoder.decode(Student.self, from:nullData)
print(nullStudent)

null 如果您使用可选项定义结构,则处理得很好。但是,如果你能避免的话,我会建议不要这样做。 Swift 提供了我所知道的最好的支持来帮助我 而不是 忘记处理 nil 可能发生的情况,但它们仍然是一个难题。

浏览 Codable 时遇到了这个问题。

所以在这里非常清楚, 如果 JSON/response 将包含 null 作为值,则它被解释为 nil。因此,出于这个原因,模型中可能包含 null 的 属性 之一应标记为可选。

例如,考虑以下 JSON 响应,

{
"name": "Steve",
"amount": null,
"address": "India"
}

模型应该如下所示,因为 amount 正在返回 null

struct Student: Codable {
    let name: String
    let amount: Double?
    let address: String
}

Suggestion:以防万一,如果您要编写 init(from decoder: Decoder) throws,请始终使用如下所示的内容作为可选属性。

init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        amount = try values.decodeIfPresent(String.self, forKey: .amount)
        //so on...
    }

即使你用try? decoder....添加do-catch块,如果失败也可以捕获。希望这很清楚!即使模型包含 5 个或更多属性,其中一些包含 null

,也很简单但很难找到问题