我在某些时间具有int值的“ products”键中有json响应,并且在某些情况下它具有数组?如何检查是否具有数组或整数?
"products": 25
要么
"products": [77,80,81,86]
我正在用这个
self.productsCount = mResp["products"] as! [Int]
但是每次没有数组时,它就会崩溃。
现在我不知道如何检查此内容,因为我对Int和Array有不同的选择?
请帮助我。谢谢
无需回到Any这里。甚至有问题的JSON都可以使用来处理Codable。您只需要继续尝试不同的类型,直到一种可行。
Any
Codable
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]