check the json response is array or int or string for a key?

  • A+
Category:Languages

I am having the json response in which "products" key sometime having the int value and some cases it had an array? How to check whether it is having array or Int?

"products": 25 

or

"products": [77,80,81,86] 

I am using this

self.productsCount = mResp["products"] as! [Int] 

but it is crashed every time when it is not having array.

Now i am not getting how to check this because i have the different option for Int and Array?

Please help me.Thanks


There is no need to fall back to Any here. Even problematic JSON like this can be handled with Codable. You just need to keep trying the different types until one works.

struct Thing: Decodable {     let products: [Int]      enum CodingKeys: String, CodingKey {         case products     }      init(from decoder: Decoder) throws {         // First pull out the "products" key         let container = try decoder.container(keyedBy: CodingKeys.self)          do {             // Then try to decode the value as an array             products = try container.decode([Int].self, forKey: .products)         } catch {             // If that didn't work, try to decode it as a single value             products = [try container.decode(Int.self, forKey: .products)]         }     } }   let singleJSON = Data(""" { "products": 25 } """.utf8)  let listJSON = Data(""" { "products": [77,80,81,86] } """.utf8)  let decoder = JSONDecoder()  try! decoder.decode(Thing.self, from: singleJSON).products   // [25] try! decoder.decode(Thing.self, from: listJSON).products     // [77, 80, 81, 86] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: