Swift JSONDecoder 错误 - 应解码 Dictionary<String, Any> 但发现了一个数组

Swift JSONDecoder error - Expected to decode Dictionary<String, Any> but found an array instead

我是 Swift 5.3 的新手,在检索嵌套的 JSON 数据时遇到问题。 我的 JSON 数据结果如下所示:

 {
    "sites":[
       {
          "site_no":"16103000",
          "station_nm":"Hanalei River nr Hanalei, Kauai, HI",
          "dec_lat_va":22.1796,
          "dec_long_va":-159.466,
          "huc_cd":"20070000",
          "tz_cd":"HST",
          "flow":92.8,
          "flow_unit":"cfs",
          "flow_dt":"2020-08-18 07:10:00",
          "stage":1.47,
          "stage_unit":"ft",
          "stage_dt":"2020-08-18 07:10:00",
          "class":0,
          "percentile":31.9,
          "percent_median":"86.73",
          "percent_mean":"50.77",
          "url":"https:\/\/waterdata.usgs.gov\/hi\/nwis\/uv?site_no=16103000"
       }
    ]
 }

我的结构是这样的:

struct APIResponse: Codable {
    let sites: APIResponseSites
}

struct APIResponseSites: Codable {
    let station_nm: String
    let stage: Float
}

我的解码 SWIFT 看起来像这样:

    let task = URLSession.shared.dataTask(with: url, completionHandler: {
        data, _, error in
        guard let data = data, error == nil else {
            return
        }
        
        var result: APIResponse?
        do {
            result = try JSONDecoder().decode(APIResponse.self, from: data)
        }
        catch {
            print("Failed to decode with error: \(error)")
        }
        
        guard let final = result else {
            return
        }
        
        print(final.sites.station_nm)
        print(final.sites.stage)
        

    })

当然,我收到一条错误消息:

Failed to decode with error: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "sites", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

我知道它与 'sites' 返回一个数组(单个数组)有关,但我不知道如何修复它。任何帮助将不胜感激。

错误消息很清楚,您需要解析对象数组而不是单个对象。

只需将您的根声明从

更改为属性
let sites: APIResponseSites

let sites: [APIResponseSites]
**1.** First "sites" is an array so replace 

let sites: APIResponseSites

with

let sites: [APIResponseSites]()


**2.** As sites is a array collection, please print value like given below:

print(final.sites.first?.station_nm ?? "")
print(final.sites.first?.stage ?? 0.0)


Final code is here:


struct APIResponse: Codable {
        let sites: [APIResponseSites]()
    }
    
    struct APIResponseSites: Codable {
        let station_nm: String
        let stage: Float
    }
    
    
    let task = URLSession.shared.dataTask(with: url, completionHandler: {
            data, _, error in
            guard let data = data, error == nil else {
                return
            }
        
            var result: APIResponse?
            do {
                result = try JSONDecoder().decode(APIResponse.self, from: data)
            }
            catch {
                print("Failed to decode with error: \(error)")
            }
            
            guard let final = result else {
                return
            }
            
            print(final.sites.first?.station_nm ?? "")
            print(final.sites.first?.stage ?? 0.0)
            
    
        })