【问题标题】:Decoding error: typeMismatch "Expected to decode Array<Any> but found a dictionary instead."解码错误:typeMismatch“预期解码 Array<Any> 但找到了字典。”
【发布时间】:2020-06-17 08:37:13
【问题描述】:

我正在努力解码 JSON。我正在尝试用

解码我的 JSON
let decodedData = try decoder.decode(Country.self, from: data)

这是可编码的结构:

struct CountryData: Codable {

    let translations: Name
    let capital: String
    let currencies: [String]

}

struct Name: Codable {
    let fr: String
}

typealias Country = [CountryData]

这是 JSON:

[
    {
        "name": "Norway",
        "topLevelDomain": [
            ".no"
        ],
        "alpha2Code": "NO",
        "alpha3Code": "NOR",
        "callingCodes": [
            "47"
        ],
        "capital": "Oslo",
        "altSpellings": [
            "NO",
            "Norge",
            "Noreg",
            "Kingdom of Norway",
            "Kongeriket Norge",
            "Kongeriket Noreg"
        ],
        "region": "Europe",
        "subregion": "Northern Europe",
        "population": 5176998,
        "latlng": [
            62.0,
            10.0
        ],
        "demonym": "Norwegian",
        "area": 323802.0,
        "gini": 25.8,
        "timezones": [
            "UTC+01:00"
        ],
        "borders": [
            "FIN",
            "SWE",
            "RUS"
        ],
        "nativeName": "Norge",
        "numericCode": "578",
        "currencies": [
            "NOK"
        ],
        "languages": [
            "no",
            "nb",
            "nn"
        ],
        "translations": {
            "de": "Norwegen",
            "es": "Noruega",
            "fr": "Norvège",
            "ja": "ノルウェー",
            "it": "Norvegia"
        },
        "relevance": "1.5"
    }
]

我得到的错误:

Decoding error: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

我不知道我做错了什么,我尝试使用 app.quicktype 工具检查我的结构,但没有发现任何问题。我是 Swift 新手,如果有人能给我一些关于如何解决这个问题的建议,那就太好了。谢谢????

【问题讨论】:

  • 为我工作...您在此处显示的 JSON 是您获得的实际 JSON 吗?
  • codingPath: [] — 你很可能真正的 JSON 不是 top 级别的数组。
  • @Sweeper 是的,我从这里的示例中复制了:rapidapi.com/apilayernet/api/…
  • 你的代码没问题,我可以得到decodeData
  • @Einn_a 你能把这行print(try JSONSerialization.jsonObject(with: data)) 添加到let decodedData 行的正上方,然后在控制台中检查数据是否与你在此处发布的数据相同。

标签: json swift codable


【解决方案1】:

你的代码是正确的

我已经在操场上尝试过了

【讨论】:

  • 感谢您的帮助!我想我已经弄清楚问题出在哪里了,这个结构没有任何问题,但是应用程序没有返回预期的 JSON,而是收到一个错误
猜你喜欢
  • 1970-01-01
  • 2019-09-11
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多