如何使用 Swiftui 检查 JSON 是否缺少键值对

How to check JSON for key value pairs missing, with Swiftui

我已经从 YouTube 解析了一个 JSON,但并不是数组中的每个项目都必须具有特定的 Key:Value 对,因此我得到了一个致命错误。我唯一的解决办法是从我的模型中注释掉某些 key:values。但是我想要一个更合适的解决方案,但我不确定动态保护丢失 key:values.

的正确方法

任何人都可以帮助我在 swiftui 中执行此操作的方法。

首先,解码 JSON 并非特定于 SwiftUI,唯一使用 SwiftUI 的时间是在与用户界面交互时。

您可以在 structclass

的自定义初始化程序中使用类似下面的内容
init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    latitude = try values.decodeIfPresent(Double.self, forKey: .latitude)
}

A decoded value of the requested type, or nil if the Decoder does not have an entry associated with the given key, or if the value is a null value.

https://developer.apple.com/documentation/swift/keyeddecodingcontainer/2893445-decodeifpresent

以下是有关解码和编码自定义类型的 Apple 文档

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types