如何使用 Swiftui 检查 JSON 是否缺少键值对
我已经解析了来自 YouTube 的 JSON,但数组中的每个项目不一定都具有特定的 Key:Value 对,因此我收到了致命错误。我唯一的解决方案是注释掉模型中的某些键:值。不过,我想要一个更合适的解决方案,但我不确定动态保护丢失的键:值的正确方法。
任何人都可以帮我提供一种在 swiftui 中执行此操作的方法。
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.
Can anyone help me with a method for doing this in swiftui.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,解码 JSON 并不特定于 SwiftUI,唯一使用 SwiftUI 的时间是与用户界面交互时。
您可以在
struct
或class
的自定义初始值设定项中使用如下所示的内容https://developer.apple.com/documentation/swift/keyeddecodingcontainer/2893445- decodeifpresent
下面是有关解码和编码自定义类型的 Apple 文档
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
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
orclass
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