Decoding different type with and without array

Viewed 68

I am trying to decode the error as follows, most of the error that I am handling in array format [String], but in few cases the error is not in array format, just a String.

If error comes in array format name comes as errors, but if it is string format then it comes as error. How could I handle this scenario?

How could I able to handle this scenario?

struct CustomError: Codable {
  let errors: [String]
}

private func errorDecoding(data : Data) {
 let decoder = JSONDecoder()
 do {
  let errorData = try decoder.decode(CustomError.self, from: data)
 } catch {
  // TODO
 }
}
1 Answers

You'd have to manually implement init(from:) and try decoding one type, failing that, decode another:

struct CustomError {
  let errors: [String]
}

extension CustomError: Decodable {
  enum CodingKeys: CodingKey { case errors, error }

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    do {
       self.errors = try container.decode([String].self, forKey: .errors) 
    } catch DecodingError.typeMismatch, 
            DecodingError.keyNotFound {
       let error = try container.decode(String.self, forKey: .error)
       self.errors = [error]
    }
  }
}

The decoding part is normal:

do {
   let error = try JSONDecoder().decode(CustomError.self, from: data)
} catch {
  // ..
}

Related