swift JSON响应中的键有时是Int,有时是String [duplicate]

yrdbyhpb  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(142)

此问题在此处已有答案

Using codable with value that is sometimes an Int and other times a String(6个答案)
19天前关闭
当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)
      }

字符串
谢谢

atmip9wb

atmip9wb1#

如果数据的类型可能会更改,您可以简单地尝试使用不同的类型解析数据,如下所示:

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
}

字符串
您也可以使用do-catch来处理解析错误,如下所示:

do {
    let intValue = try container.decode(Int.self, forKey: .Quantity)
} catch DecodingError.typeMismatch {
    let stringValue = try container.decode(String.self, forKey: .Quantity)
} catch {
    // Handle an error here
}

相关问题