JSON 响应中的键有时是 Int,有时是 String

问题描述 投票:0回答:1

key的数据类型有时是Int/string时如何解析。下面是我到目前为止尝试过但不起作用的代码:

  do {
       // let value = try String(container.decode(Int.self, forKey: .Quantity))
          let value = try container.decode(Int.self, forKey: .Quantity)
          Quantity = value == 0 ? nil : String(value)
      } catch DecodingError.typeMismatch {
        Quantity = try container.decode(String.self, forKey: .Quantity)
      }

谢谢

ios json swift api codable
1个回答
0
投票

如果数据类型可能发生变化,您可以简单地尝试用不同的类型解析数据,如下所示:

if let intValue = try? container.decode(Int.self, forKey: .Quantity) {
    // The integer value here
} else if stringValue = try? container.decode(String.self, forKey: .Quantity) {
    // The string value here
}
© www.soinside.com 2019 - 2024. All rights reserved.