检查json响应是数组还是int或字符串作为键? [英] check the json response is array or int or string for a key?

查看:87
本文介绍了检查json响应是数组还是int或字符串作为键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json响应,其中的"products"键有时具有int值,在某些情况下它具有数组? 如何检查它是否具有数组或整数?

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

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

我正在使用

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

但是每次没有数组时都会崩溃.

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

现在我不知道如何检查这一点,因为我对Int和Array有不同的选择?

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

请帮助我.谢谢

推荐答案

此处无需回退到Any.甚至有问题的JSON都可以使用Codable进行处理.您只需要继续尝试不同的类型,直到一种可行为止.

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]

这篇关于检查json响应是数组还是int或字符串作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆