如何筛选JSON数据解析器

时间:2018-01-29 06:43:31

标签: json swift swift3 filter alamofire

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

1 个答案:

答案 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对象中。