本文介绍了在SwiftyJson中过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SwiftyJson对象.

I have one SwiftyJson object.

我无法过滤该数组.我已经尝试过此解决方案 https://stackoverflow.com/a/37497170/4831567 .但是我的json格式与众不同,这就是为什么不起作用的原因.

I can not filter that array. I have tried this solution https://stackoverflow.com/a/37497170/4831567. But my json format is different that's why not working.

[
    {
        "name": "19860",
        "header": {
            "start_time": "1519270200",
            "end_time": "1519299000",
            "state": "lunch"
        },
        "alerts": "1",
        "venue": {
            "location": "Delhi, India",
            "timezone": "+05:30"
        },
        "srs_category": [
            0,
            1
        ]
    },
    {
        "name": "19861",
        "header": {
            "start_time": "1519270200",
            "end_time": "1519299000",
            "state": "Dinner"
        },
        "alerts": "1",
        "venue": {
            "location": "Mumbai, India",
            "timezone": "+05:30"
        },
        "srs_category": [
            1,
            3
        ]
    },
    {
        "name": "19862",
        "header": {
            "start_time": "1519270200",
            "end_time": "1519299000",
            "state": "lunch"
        },
        "alerts": "1",
        "venue": {
            "location": "Surat, India",
            "timezone": "+05:30"
        },
        "srs_category": [
            0,
            2
        ]
    }
]

我想找到srs_category包含1的对象.我知道可以通过循环和条件来实现.但是我想通过NSPredicate.如果可以的话,请帮帮我.

i want to find that object that srs_category contain 1. I know it is possible by looping and condition. But i want via NSPredicate. If it is possible then please help me.

谢谢.

推荐答案

使用Swift本机函数而不是NSPredicate

Use a Swift native function rather than NSPredicate

data表示从某处接收的Data对象

data represents the Data object received from somewhere

do {
    if let json = try JSONSerialization.jsonObject(with:data) as? [[String:Any]] {
        let srsCategory1 = json.first(where: { dict -> Bool in
            guard let array = dict["srs_category"] as? [Int] else { return false }
            return array.contains(1)
        })
        print(srsCategory1 ?? "not found")
    }
} catch {
    print(error)
}

如果有多个可以匹配条件的项目,请用filter替换first.然后结果是一个非可选数组.

If there are multiple items which can match the condition replace first with filter. Then the result is a non-optional array.

这篇关于在SwiftyJson中过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 17:16