[英]Trouble parsing nested JSON in Swift 5 using Decodable
我有一個 API,它返回結構類似於下面的 JSON。 為簡單起見,我刪除了 JSON 中的所有兄弟字典,以便我們可以專注於解析單個屬性的核心目標。 我似乎無法弄清楚為什么它不會解析。
API JSON:
{
"players": {
"uniqueUUIDwouldGoHere": {
"ace": {
"operatorpvp_kills": 11
}
}
}
}
我的 Swift 結構體是這樣寫的:
public struct opsResponse: Decodable {
var players : [String: opsInner]
enum CodingKeys: String, CodingKey {
case players = "players"
}
}
public struct opsInner: Decodable {
var ace : [String: ace]
enum CodingKeys: String, CodingKey {
case ace = "ace"
}
}
public struct ace: Decodable {
var operatorpvp_kills : Int = 0
enum CodingKeys: String, CodingKey {
case operatorpvp_kills = "operatorpvp_kills"
}
}
最后,URLSession 解碼器部分:
let decoder = JSONDecoder()
let json = try decoder.decode(opsResponse.self, from: data)
來自catch
錯誤消息:
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "players", intValue: nil), _JSONKey(stringValue: "uniqueUUIDwouldGoHere", intValue: nil), CodingKeys(stringValue: "ace", intValue: nil), _JSONKey(stringValue: "operatorpvp_kills", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
更新:
我將: var ace : [String: ace]
更改為var ace : ace
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.