JSON 响应 tranArr
[{
"total_amt" : -10000,
"tran_type" : "C3",
"pay_type" : "05",
"tran_time" : "20180125 133122",
"point_total" : 0
},
{
"total_amt" : -1004,
"tran_type" : "C5",
"pay_type" : "05",
"tran_time" : "20180124 163602",
"point_total" : 0
}]
=====================
我想过滤tran_type =“C3”
我该怎么办?
"total_amt" : -10000,
"tran_type" : "C3",
"pay_type" : "05",
"tran_time" : "20180125 133122",
"point_total" : 0
答案 0 :(得分:0)
尝试这样的事情:
let string = "[{ \"total_amt\" : -10000,\"tran_type\" : \"C3\", \"pay_type\" : \"05\", \"tran_time\" : \"20180125 133122\", \"point_total\" : 0},{\"total_amt\" : -1004,\"tran_type\" : \"C5\", \"pay_type\" : \"05\", \"tran_time\" : \"20180124 163602\", \"point_total\" : 0 }]"
// Convert string to Data
let jsonData = string.data(using: .utf8)!
do {
// Serialize the json Data and cast it into Array of Dictionary
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [[String: Any]]
// Apply filter on `tran_type`
let tranArr = jsonObject?.filter({ (dictionary) -> Bool in
dictionary["tran_type"] as? String == "C3"
})
print(tranArr)
} catch {
print(error)
}
已过滤的结果将位于tranArr
对象中。