首页 > 解决方案 > 在 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)
            }
        }
        
    }
}

标签: jsonswiftparsingcodablerapidapi

解决方案


从打印输出中,这是您应该使用的数据结构:

struct Country: Codable {
    let country, code: String
    let confirmed, recovered, critical, deaths: Int
    let latitude, longitude: Double
    let lastChange, lastUpdate: Date  // <-- or String
}

推荐阅读