json - 如何过滤 API 响应以在 Swift 中包含/排除 TableView 中的某些数据
问题描述
我正在尝试排除我从 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,有人可以帮忙吗?
解决方案
你需要
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)
}
推荐阅读
- html - React-Select 打破下拉菜单
- c - 用 C 语言实现 2D Grid Network ( Graph ) 及其邻接矩阵
- java - Java8 流无法解析变量
- react-native - 使用 react-navigation 和 react-native-fluid-transitions 进行排毒 e2e 测试 - 期望 .toBeVisible 失败
- jquery - 未定义 onclick 功能
- postgresql - 如何在pgadmin中备份表包含序列
- python - 尝试将 PCM 转换为频率图,但结果在 0 附近看起来很奇怪
- laravel - 使用 laravel mix 函数未声明错误
- post - 在 Django Rest Framework Swagger 中发布正文参数
- javascript - React Native - setState 和 setNativeProps 有什么区别?