Search code examples
iosjsonswiftcodable

A key in JSON response sometimes Int and sometimes comes as String


How to parse when data type of key is random sometimes comes as Int/string. Below is my code what have tried so far but not working:

  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)
      }

Thanks


Solution

  • If the type of data may change, you can simply try parsing the data with a different type, as follows:

    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
    }
    

    You can also use the do-catch to handle parsing errors like this:

    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
    }