我正在制作一个小应用程序来练习将 JSON 解析为表格 View ,并且我正在使用 Ticketmaster API。 This is the JSON ,这些是我设置的结构:
struct Welcome: Decodable {
let embedded: WelcomeEmbedded
enum CodingKeys: String, CodingKey{
case embedded = "_embedded"
}
}
struct WelcomeEmbedded: Decodable {
let events: [Event]
}
struct Event: Decodable {
let name: String
let dates: Dates
let eventUrl: String?
let embedded: EventEmbedded
enum CodingKeys: String, CodingKey {
case name
case dates
case eventUrl
case embedded = "_embedded"
}
}
struct EventEmbedded: Decodable {
let venue: Venue
}
struct Dates: Decodable {
let start, end: End
}
struct Venue: Decodable {
let name: String
}
在添加值之前 let embedded: EventEmbedded
到 Event
结构,一切正常,但在添加该行后,运行应用程序时出现错误:
Error decoding JSON: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "_embedded", intValue: nil), CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "_embedded", intValue: nil), CodingKeys(stringValue: "venue", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
我想知道单独添加该行是如何导致错误的,这与我有一个名为 embedded
的值有关吗?在两个结构中( Welcome
和 Event
),并且都使用编码键 _embedded
?
对于一些额外的细节,为了解析 JSON,我有一个变量 var eventData = [Event]()
并在 viewDidLoad
中调用此函数填充 eventData
具有必要的数据:
fetchData(url: apiUrl) { (result: FetchResult<Welcome>) -> (Void) in
switch result {
case .success(let object): self.eventData = object.embedded.events
case .failure(let error): print("\nError decoding JSON: \(error)\n\n")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
错误还显示 CodingKeys(stringValue: "venue", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.
.但是看json,venue
下的数据与其他值的结构相同,它们不会给我错误。
在这里我可以做些什么不同的事情来回到正轨?
最佳答案
请学会阅读Codable
错误。它们非常、非常、非常具有描述性。
Error decoding JSON: typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "_embedded", intValue: nil), CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "_embedded", intValue: nil), CodingKeys(stringValue: "venue", intValue: nil)], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))
-
typeMismatch
是错误类型 -
CodingKeys(stringValue: "_embedded", CodingKeys(stringValue: "events"), CodingKeys(stringValue: "_embedded"), CodingKeys(stringValue: "venue")
是关键路径(_embedded/events/_embedded/venue
) Expected to decode Dictionary<String, Any> but found an array instead
是错误信息。-
Expected
是您建议的错误类型。 found
是实际类型。A
dictionary
是结构,一个array
是结构的数组。
-
更改 EventEmbedded
到
struct EventEmbedded: Decodable {
let venue: [Venue]
}
关于ios - 解码 JSON 时在两个结构中使用相同的编码 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391435/