首页 > 解决方案 > 如何过滤 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,有人可以帮忙吗?

标签: jsonswiftapi

解决方案


你需要

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)
}

推荐阅读