【问题标题】:Error with creating an Array of JSON objects in swift快速创建 JSON 对象数组时出错
【发布时间】:2021-05-19 20:30:27
【问题描述】:

我正在尝试解析一个 JSON 字符串,它是多个“国家/地区”的集合。我创建了一个结构,表示每个 JSON 对象中的字段,然后创建一个用于数组的结构。但是我不断收到以下错误

Error: cannot convert value of type 'CountryList' to specified type 'Country'

这是我的代码(用 Swift Playgrounds 编写)

import Cocoa
let body = """
{"Countries":
[
  {
    "id": 1,
    "name": "USA",
    "capitalCity": 5,
  },
  {
    "id": 2,
    "name": "France",
    "capitalCity": 5,
  }]}
""".data(using: .utf8)

struct Country: Codable {

    let id: Int
    let name: String
    let capitalCity: Int
 
    
}
struct CountryList: Codable {
    
    var Countries: [Country]
    
}



let countryJson: Country = try! JSONDecoder().decode(CountryList.self, from: body!)
print(countryJson)

感谢您的帮助。

【问题讨论】:

  • 您已将countryJson 声明为Country 类型,但您正在解码CountryList - 您想要let countryJson: CountryList = ...

标签: ios json swift


【解决方案1】:

替换此行

let countryJson: Country = try! JSONDecoder().decode(CountryList.self, from: body!)

用这个:

let countryJson: CountryList = try! JSONDecoder().decode(CountryList.self, from: body!)

【讨论】:

  • 而且你也不需要显式声明类型,因为它可以被推断出来。
  • 你是对的。这不是必需的。但我总是更喜欢将类型留在我的代码中,以便让我的开发人员清楚。
猜你喜欢
  • 2018-03-06
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
相关资源
最近更新 更多