I've parsed a JSON from YouTube and not every item in the array necessarily have certain Key:Value pairs, thus I get a fatal error. My only solution has been to comment out certain key:values from my Model. However I'd like a more appropriate solution but I'm not sure the right way to dynamically guard for missing key:values.

有谁能帮我在swiftui中实现这一点的方法吗.

推荐答案

First, decoding a JSON is not specific to SwiftUI, the only time SwiftUI is used is when interacting with the User Interface.

You can use something like below in a custom initializer for your struct or class

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    latitude = try values.decodeIfPresent(Double.self, forKey: .latitude)
}

请求类型的解码值,如果解码器没有与给定密钥关联的条目,或者如果该值为空值,则为nil.

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

Below is the Apple documentation on decoding and encoding custom types

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

Json相关问答推荐

JOLT拉平数组

为什么terraform不缩小这个策略JSON?'

如何使用JQ打印每个根级对象键一行?

当有2个嵌套数组时展平复杂的JSON

PowerShell女士:如何处理json对象?

go 语言中的 JSON 到 XML

如何将属性拆分为嵌套的JSON内容?

取消嵌套数组并将数组名称添加为附加字段

如何将复杂的 JSON 反序列化为 Rust 类型?

将具有多个级别的 json 读入 DataFrame [python]

将 colly 包输出文本添加到 golang 中的映射

解析 JSON API 响应

在 JavaScript 中从 Json 数据中删除反斜杠

如何将 LinkedHashMap 转换为自定义 java 对象?

jquery用json数据填充下拉列表

jQuery循环.each()JSON键/值不起作用

waitUntilAllTask​​sAreFinished 错误 Swift

从 Json 对象 Android 中获取字符串值

js 中奇怪的 JSON 解析行为,Unexpected token :

春天:返回@ResponseBodyResponseEntity>