我正在尝试排除从 API 响应中收到的一些数据,
API 响应:
{"status":"ok","answer":[{
address = Newyork;
comments = test;
"contact_name" = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="157c7a66557c7a663b767a78" rel="noreferrer noopener nofollow">[email protected]</a>";
status = "4";
},
{
address = Ohio;
comments = test;
"contact_name" = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254c4a56654c4a560b464a48" rel="noreferrer noopener nofollow">[email protected]</a>";
"status" = "3";
},
{
address = cityname;
comments = test;
"contact_name" = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c55534f7c55534f125f5351" rel="noreferrer noopener nofollow">[email protected]</a>";
status = "3";
},
{
address = Washington;
comments = test;
"contact_name" = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="640d0b17240d0b174a070b09" rel="noreferrer noopener nofollow">[email protected]</a>";
status = "4";
}
)
)
我想要实现的是过滤此响应,并仅查看 TableView 中状态为“4”的订单。
这是我迄今为止尝试过的:
func getOrdersHistory() {
DispatchQueue.main.async {
let headers = [
"content-type" : "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99"
]
let user = CoreDataFetcher().returnUser()
let email = user.email!
let postData = NSMutableData(data: "data={\"email\":\"\(email)\",\"type_id\":\"2\"}".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://www.someApi/Orders")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print(responseString)
let dict = self.convertToDictionary(text: responseString)
print(dict?["answer"] as Any)
self.responseArray = (dict?["answer"] as! NSArray) as! [ConfirmedOrders.JSONDictionary]
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
})
dataTask.resume()
}
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
这样,我就可以进入 TableView,无论它们的状态如何, 有人可以帮忙吗?
最佳答案
根据您的数据集并使用纯 Swift 数组和字典,您可以像这样简单地进行过滤:
func getConfirmedOrders(in dict: [String:Any]) -> [[String:Any]] {
guard
let answers = dict["answer"] as? [[String:Any]]
else { print("Answer key not present"); return [] }
//Your basic filter operation
let filtered = answers.filter { (answer) -> Bool in
return answer["status"] as? String == "4"
}
return filtered
}
这只是正确的类型转换,然后对其应用过滤
操作。
像这样简单地使用它:
self.responseArray = self.getConfirmedOrders(in: dict)
DispatchQueue.main.async {
self.tableView.reloadData()
}
但是,我发现您的 responseArray
的类型为 [ConfirmedOrders.JSONDictionary]
。
因此,要么将 getConfirmedOrders(from:)
更改为返回 [ConfirmedOrders.JSONDictionary]
,要么将 responseArray
更改为 [[String :任意]]
。
Playground 示例
let jsonString = """
{"status":"ok","answer":[{"address":"Newyork","comments":"test","contact_name":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e37312d1e37312d703d3133" rel="noreferrer noopener nofollow">[email protected]</a>","status":"4"},{"address":"Ohio","comments":"test","contact_name":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2abadb182abadb1eca1adaf" rel="noreferrer noopener nofollow">[email protected]</a>","status":"3"},{"address":"cityname","comments":"test","contact_name":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="137a7c60537a7c603d707c7e" rel="noreferrer noopener nofollow">[email protected]</a>","status":"3"},{"address":"Washington","comments":"test","contact_name":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2224380b22243865282426" rel="noreferrer noopener nofollow">[email protected]</a>","status":"4"}]}
"""
if let data = jsonString.data(using: .utf8) {
do {
//basically what you have in `convertToDictionary(text:)`
let dict = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let filtered = getConfirmedOrders(in: dict)
print(filtered)
}
catch {
print(error)
}
}
建议:
- 使用 Codable 模型而不是 Swift 数组和字典
- 使用 Swift
Array
而不是NSArray
,同样使用 Swift Dictionary 而不是NSDictionary
关于json - 如何过滤 API 响应以在 Swift 中包含/排除 TableView 中的一些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55891118/