Filter Data in SwiftyJson

做~自己de王妃 提交于 2019-12-11 16:16:49

问题


I have one SwiftyJson object.

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
        ]
    }
]

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.

Thank You.


回答1:


Use a Swift native function rather than NSPredicate

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)
}

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




回答2:


Here is easy way to use SwiftyJSON:

    let filtered = JSON(yourArray).arrayValue.filter({
        $0["srs_category"].arrayValue.map({ $0.intValue }).contains(1)
    })


来源:https://stackoverflow.com/questions/48925619/filter-data-in-swiftyjson

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