如何过滤这些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";
}
}
答案 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
。