我正在尝试从API响应中排除一些我收到的数据,
API响应:
{"status":"ok","answer":[{
address = Newyork;
comments = test;
"contact_name" = "ios@ios.com";
status = "4";
},
{
address = Ohio;
comments = test;
"contact_name" = "ios@ios.com";
"status" = "3";
},
{
address = cityname;
comments = test;
"contact_name" = "ios@ios.com";
status = "3";
},
{
address = Washington;
comments = test;
"contact_name" = "ios@ios.com";
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 有人可以帮忙吗?
答案 0 :(得分:1)
根据您的数据集并使用纯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
}
这只是关于正确的类型转换,然后对其应用filter
操作。
像这样简单地使用它:
self.responseArray = self.getConfirmedOrders(in: dict)
DispatchQueue.main.async {
self.tableView.reloadData()
}
但是,我发现您的responseArray
的类型为[ConfirmedOrders.JSONDictionary]
。
因此,请更改getConfirmedOrders(from:)
以返回[ConfirmedOrders.JSONDictionary]
或将您的responseArray
更改为[[String:Any]]
类型。
let jsonString = """
{"status":"ok","answer":[{"address":"Newyork","comments":"test","contact_name":"ios@ios.com","status":"4"},{"address":"Ohio","comments":"test","contact_name":"ios@ios.com","status":"3"},{"address":"cityname","comments":"test","contact_name":"ios@ios.com","status":"3"},{"address":"Washington","comments":"test","contact_name":"ios@ios.com","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)
}
}
Array
代替NSArray
,类似地使用Swift Dictionary代替NSDictionary
答案 1 :(得分:0)
您需要
do {
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try dec.decode(Root.self, from: data)
// here filter like e.x
let filtered = res.answer.filter { $0.status == "4" }
}
catch{
print(error)
}
struct Root: Codable {
let status: String
let answer: [Answer]
}
struct Answer: Codable {
let address, comments, contactName, status: String
}
如果您需要摆脱Root
,请这样做
do {
guard let data = data else { return }
let dic = try JSONSerialization.jsonObject(with:data, options: []) as! [String:Any]
let dataAns = try JSONSerialization.data(withJSONObject:dic["answer"]!, options: [])
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try dec.decode([Answer].self, from: dataAns)
// here filter like e.x
let filtered = res.filter { $0.status == "4" }
}
catch{
print(error)
}