在 RapidAPI 中解析嵌入式数组 (Swift)
Parsing embedded arrays in RapidAPI (Swift)
我正在 RapidAPI 上查看有关 covid19 的 API。我测试了端点并显示了这个结果:
[0:
"country":"Canada"
"provinces":[
0:{
"province":"Alberta"
"confirmed":754
"recovered":0
"deaths":9
"active":0
}...etc]
"latitude":56.130366
"longitude":-106.346771
"date":"2020-04-01"
}
]
非常简单。我想解析“省”段,所以在 xcode 中我设置了几个这样的模型:
struct Country: Codable{
let country: String
let provinces: [Province]
}
struct Province: Codable{
let province: String
let confirmed: Int
let recovered: Int
let deaths: Int
let active: Int
}
我相信这是正确的,但无法解析。只有当我注释掉这一点时它才有效:
struct Country: Codable{
let country: String
//let provinces: [Province]
}
意味着我可以打印出国家的名称,但只有当省份对象被注释掉时。这让我觉得我的模型有问题。我在这里做错了什么?我查看了其他示例,这应该有效...我很确定。
编辑:我将添加更多代码以更清楚地说明我在做什么:
override func viewDidLoad() {
super.viewDidLoad()
Service.shared.getInfo(requestURL: "url", host: "host", key: "12345", needsKey: true) { data in
if let data = data{
if let p = try? JSONDecoder().decode([Country].self, from: data){
//get the data and set it to a string
let provinceName: String = p[0].provinces[0].province
self.provinceStr = provinceName
}
DispatchQueue.main.async {
[unowned self] in
//print the string
print(self.provinceStr)
}
}
}
}
根据打印输出,这是您应该使用的数据结构:
struct Country: Codable {
let country, code: String
let confirmed, recovered, critical, deaths: Int
let latitude, longitude: Double
let lastChange, lastUpdate: Date // <-- or String
}
我正在 RapidAPI 上查看有关 covid19 的 API。我测试了端点并显示了这个结果:
[0:
"country":"Canada"
"provinces":[
0:{
"province":"Alberta"
"confirmed":754
"recovered":0
"deaths":9
"active":0
}...etc]
"latitude":56.130366
"longitude":-106.346771
"date":"2020-04-01"
}
]
非常简单。我想解析“省”段,所以在 xcode 中我设置了几个这样的模型:
struct Country: Codable{
let country: String
let provinces: [Province]
}
struct Province: Codable{
let province: String
let confirmed: Int
let recovered: Int
let deaths: Int
let active: Int
}
我相信这是正确的,但无法解析。只有当我注释掉这一点时它才有效:
struct Country: Codable{
let country: String
//let provinces: [Province]
}
意味着我可以打印出国家的名称,但只有当省份对象被注释掉时。这让我觉得我的模型有问题。我在这里做错了什么?我查看了其他示例,这应该有效...我很确定。
编辑:我将添加更多代码以更清楚地说明我在做什么:
override func viewDidLoad() {
super.viewDidLoad()
Service.shared.getInfo(requestURL: "url", host: "host", key: "12345", needsKey: true) { data in
if let data = data{
if let p = try? JSONDecoder().decode([Country].self, from: data){
//get the data and set it to a string
let provinceName: String = p[0].provinces[0].province
self.provinceStr = provinceName
}
DispatchQueue.main.async {
[unowned self] in
//print the string
print(self.provinceStr)
}
}
}
}
根据打印输出,这是您应该使用的数据结构:
struct Country: Codable {
let country, code: String
let confirmed, recovered, critical, deaths: Int
let latitude, longitude: Double
let lastChange, lastUpdate: Date // <-- or String
}