如何在swift中过滤json对象?

时间:2016-10-28 09:45:18

标签: ios arrays json swift parsing

如何过滤这些json对象?我的意思是我只想打印那些id等于3的患者。

var patients: Array<AnyObject>? if let obj: AnyObject = manager?.responseObject as AnyObject? {
            if let pats = obj["patients"] as! Array<AnyObject>? {
                patients = pats
            }
        }

这是我的打印变量

{
    patients =     (
                {
            city = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            district = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            firstname = fdfsdf;
            lastname = dsfgsdfg;
            "patient_id" = 1064;
            "patient_status" = 3;
            "register_id" = "\U0430\U043083040411";
        }
                {
            city = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            district = "\U0411\U0430\U044f\U043d\U0445\U043e\U043d\U0433\U043e\U0440";
            firstname = dwfw;
            lastname = dsfsdf;
            "patient_id" = 1056;
            "patient_status" = 1;
            "register_id" = "\U0443\U044399111134";
        }
}

1 个答案:

答案 0 :(得分:2)

请尽可能降低类型。

所有类型都比AnyObject更具体,JSON词典始终为[String:AnyObject],JSON数组为Array<[String:AnyObject]>。仅当数组包含另一个数组或嵌套更多时才使用Array<AnyObject>

使用filter功能过滤患者。

var patients = Array<[String:AnyObject]>()

if let obj = manager?.responseObject as? [String:AnyObject] {
   if let pats = obj["patients"] as? Array<[String:AnyObject]> {
       patients = pats.filter { $0["patient_status"] as! Int == 3 } 
   }
}

注意:在Swift 3中AnyObject已替换为Any