Decoding different type with and without array

邮差的信 提交于 2021-02-10 05:08:41

问题


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:


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 {
  // ..
}



来源:https://stackoverflow.com/questions/64307042/decoding-different-type-with-and-without-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!