ios - 解析嵌套 JSON 时出错(Swift 5)
问题描述
我正在尝试解码 JSON,但在嵌套值方面遇到了一些困难。下图是我正在检索的 JSON 的样子:
我的目标是在“价格”下的“常规市场开放”下获得“原始”价值。我的结构如下所示:
struct Response: Codable {
let symbol: String?
let price: [Price]?
}
struct Price: Codable {
let quoteSourceName: String?
let regularMarketOpen: [regularMarketOpen]?
}
struct regularMarketOpen: Codable {
let fmt: String?
}
无论出于何种原因,我不断收到这样的错误:
ERROR: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "price", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
这是我的检索方法的问题吗?谢谢!
解决方案
regularMarketOpen
并且price
似乎是一个对象。但let regularMarketOpen: [regularMarketOpen]?
意味着它是一个数组。
解析时要小心,{}
是对象,[]
是数组。
尝试这个:
struct Response: Codable {
let symbol: String?
let price: Price?
}
struct Price: Codable {
let quoteSourceName: String?
let regularMarketOpen: regularMarketOpen?
}
struct regularMarketOpen: Codable {
let fmt: String?
}
为避免此类错误,您可以使用https://app.quicktype.io生成模型结构。
快乐解析:)
推荐阅读
- networkx - 由networkx中的边缘号控制的广度优先搜索?
- tensorflow - 如何在 TensorFlow 中展开 Xception 层
- mysql - MySQL 'IS NULL' 在 JOIN 查询中将值设置为 NULL
- scala - 如何通过在火花中使用 IN 子句传递另一个列值来检索列值
- c# - 我怎样才能重构它,以便具有 CardStack 脚本的多个游戏对象独立递增
- c# - C# 如何将 unHex 转换为字符串
- sharepoint - Azure 数据工厂和个人或组 SharePoint 数据类型
- javafx - JavaFX CSS 选择框和组合框
- wordpress - 在父类别上显示 Woocommerce 子类别的描述
- javascript - 谷歌表格电子邮件发送功能不起作用