Swift JSONDecoder错误-预期对Dictionary< String,Any>进行解码但是找到了一个数组 [英] Swift JSONDecoder error - Expected to decode Dictionary<String, Any> but found an array instead

查看:134
本文介绍了Swift JSONDecoder错误-预期对Dictionary< String,Any>进行解码但是找到了一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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)
        

    })

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

无法解码,并显示以下错误:typeMismatch(Swift.Dictionary< Swift.String,Any> ;、Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:"sites",intValue:nil)],debugDescription:预期解码字典< String,Any>但是找到了一个数组.",underlyingError:零))

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))

我知道这与站点"返回一个数组(单个数组)有关,但是我不知道如何解决它.任何帮助将不胜感激.

推荐答案

错误消息很明显,您需要解析对象数组而不是单个对象.

The error message it is pretty clear you need to parse an array of objects instead of a single object.

只需更改您的根声明属性,即可

Just change your root declaration property from

let sites: APIResponseSites

let sites: [APIResponseSites]

这篇关于Swift JSONDecoder错误-预期对Dictionary&lt; String,Any&gt;进行解码但是找到了一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆