在 JSON 中解析时;将模型属性设置为可选或强制性是最佳做法吗?

When parsing in JSON; is it best practice to have your model properties as optionals or mandatory?

我正在 Swift 中加载本地 json 文件并使用网站 https://quicktype.io/ 帮助我快速构建结构。

他们给你的默认值是 response/welcome 结构有可选的内容;你可以关闭它。

即:

// JSON:
{
    "numbers": [ 1, 2, 3 ],
    "orders": [] // this is deliberate the orders can be empty at default; but can be added to in the app; for context, they will be Ints.
}

quicktype 给我:

// I've renamed Welcome in my app to Response
struct Welcome: Codable {
    var numbers: [Int]?
    var orders: [JSONAny]?
}

然后我可以使用 Swift JSON解码来解码我的对象。

即:

// get data from bundle  (not shown)

        let data = try Data(contentsOf: url)
        XCTAssertTrue(data.count > 0)

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .deferredToDate
        decoder.keyDecodingStrategy = .convertFromSnakeCase

        let response = try decoder.decode(Response.self, from: data)

是的,我知道,因为这是本地数据,我可以默认将所有内容设为非可选,因为我知道内容;但我曾经将数据保存到磁盘——我无法知道数据是否得到 corrupted/mutated,等等

在我的代码中,我将输入视为可选;根据给出的结构。

然而,这意味着我必须在需要使用它们的任何时候 unwrap/unguard 变量;这使得使用 filter、map、reduce 等变得更加困难。

我正在考虑将它们全部强制执行以解决这个问题。

我想知道处理内部模型 JSON 的最佳实践是什么?

是否让模型的属性默认可选?

如果是的话;如果输入确实像一个空数组或 nil,你将如何检查 response 的内容是否存在?

谢谢

如果您可以控制输入 JSON,那么不要将它们用作可选项是有意义的,因为正如您所说,您不需要在每次使用它们时都打开模型。

And if so; how would you check that the contents of response are there if indeed the input is like an empty array or nil?

如果您尝试解码不兼容的模型,将抛出错误。