【发布时间】:2021-05-19 20:30:27
【问题描述】:
我正在尝试解析一个 JSON 字符串,它是多个“国家/地区”的集合。我创建了一个结构,表示每个 JSON 对象中的字段,然后创建一个用于数组的结构。但是我不断收到以下错误
Error: cannot convert value of type 'CountryList' to specified type 'Country'
这是我的代码(用 Swift Playgrounds 编写)
import Cocoa
let body = """
{"Countries":
[
{
"id": 1,
"name": "USA",
"capitalCity": 5,
},
{
"id": 2,
"name": "France",
"capitalCity": 5,
}]}
""".data(using: .utf8)
struct Country: Codable {
let id: Int
let name: String
let capitalCity: Int
}
struct CountryList: Codable {
var Countries: [Country]
}
let countryJson: Country = try! JSONDecoder().decode(CountryList.self, from: body!)
print(countryJson)
感谢您的帮助。
【问题讨论】:
-
您已将
countryJson声明为Country类型,但您正在解码CountryList- 您想要let countryJson: CountryList = ...