类型不匹配的Swift JSON

问题描述

我认为我正确地创建了该结构,但是它给出了错误

typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预期对Array进行解码,但找到了一个字典。”,底层错误:无))

型号:

struct veriler : Codable {
    let success : Bool
    let result : [result]
    
}

struct result : Codable {
    let country : String
    let totalCases : String
    let newCases : String
    let totalDeaths : String
    let newDeaths : String
    let totalRecovered : String
    let activeCases : String
}

JSON数据:

{
  "success": true,"result": [
    {
      "country": "China","totalcases": "80,881","newCases": "+21","totaldeaths": "3,226","newDeaths": "+13","totalRecovered": "68,709","activeCases": "8,946"
    },{
      "country": "Italy","totalcases": "27,980","newCases": "","totaldeaths": "2,158","newDeaths": "","totalRecovered": "2,749","activeCases": "23,073"
    },"..."
  ]
}

解码:

let decoder = JSONDecoder()
        do {
            let country = try decoder.decode([result].self,from: data!)
          for i in 0..<country.count {
            print (country[i].country)
          }
        } catch {
          print(error)
        }

解决方法

首先,您需要通过指定自定义result来修改CodingKeys结构(请注意模型中的totalCases和JSON中的totalcases之间的不匹配):

struct result: Codable {
    enum CodingKeys: String,CodingKey {
        case country,newCases,newDeaths,totalRecovered,activeCases
        case totalCases = "totalcases"
        case totalDeaths = "totaldeaths"
    }
    
    let country: String
    let totalCases: String
    let newCases: String
    let totalDeaths: String
    let newDeaths: String
    let totalRecovered: String
    let activeCases: String
}

然后,您需要解码veriler.self而不是[result].self

let decoder = JSONDecoder()
do {
    let result = try decoder.decode(veriler.self,from: data!)
    let countries = result.result
    for i in 0 ..< countries.count {
        print(countries[i].country)
    }
} catch {
    print(error)
}

注意:我建议遵循Swift准则,并使用ResultVeriler之类的名称结构(仅实例应小写)。