【问题标题】:How to fetch the data from a Json file when it has a number as the name of the structure in swift?当 Json 文件有一个数字作为 swift 结构的名称时,如何从 Json 文件中获取数据?
【发布时间】:2020-07-23 16:03:00
【问题描述】:

这种Json文件结构名为0时如何获取数据?

由于 Swift 或我可能知道的任何编程语言的性质不允许开发人员使用数字作为结构名称。

我想从中获取数据的位置:

*0.confirmed

Json 代码:

  [ { "country": "Cambodia", "code": "KH", "confirmed": 198,
     "recovered": 142, "critical": 1, "deaths": 0, "latitude": 12.565679,
     "longitude": 104.990963, "lastChange": "2020-07-23T06:18:34+02:00",
    "lastUpdate": "2020-07-23T16:30:03+02:00" } ]

我的快速结构:

struct CoronaVirusData: codable {
    var Countries: 0
}

struct 0:  codable{
    var critical: Int
    var confirmed: Int
    var deaths:Int
    var recovered:Int
    var lastUpdate: String

【问题讨论】:

  • 我使用 Json Viewer Awesome 来查看我想要获取的数据的位置,它显示为 0.confirmed。这让我有点困惑。

标签: json swift api


【解决方案1】:

为什么要将 struct 命名为 0?您只是试图解码一个数组,而不是一个名为 0 的元素。

为您的struct 取一个有意义的名称,然后将数组类型简单地传递给JSONDecoder.decode

struct CoronaVirusData: Codable {
    let critical: Int
    let confirmed: Int
    let deaths: Int
    let recovered: Int
    let lastUpdate: String
}

// Test code
let json = """
[ { "country": "Cambodia", "code": "KH", "confirmed": 198,
   "recovered": 142, "critical": 1, "deaths": 0, "latitude": 12.565679,
   "longitude": 104.990963, "lastChange": "2020-07-23T06:18:34+02:00",
  "lastUpdate": "2020-07-23T16:30:03+02:00" } ]
""".data(using: .utf8)!

do {
    let decoded = try JSONDecoder().decode([CoronaVirusData].self, from: json)
} catch {
    print(error)
}

【讨论】:

  • 我们不应该假设结构的名称与以Json格式声明的结构相同吗?我试图将结构声明为您的结构,这是错误。 error block 2: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
  • @vatanachhorn 不,您的类型名称与您的 JSON 外观无关。属性名称应该与 JSON 键匹配 - 但即使您声明符合 enumCodingKey 也不是必需的。
  • @vatanachhorn 用固定代码检查我的更新答案
  • 非常感谢兄弟。我明天会深入研究它。有点理解,但不是很清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多