首页 > 解决方案 > 解析嵌套 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))

这是我的检索方法的问题吗?谢谢!

标签: iosjsonswift

解决方案


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生成模型结构。

快乐解析:)


推荐阅读