【发布时间】:2020-06-17 08:37:13
【问题描述】:
我正在努力解码 JSON。我正在尝试用
解码我的 JSONlet 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行的正上方,然后在控制台中检查数据是否与你在此处发布的数据相同。