swift 3中只需要来自json的键(状态)和值(0)

Posted

技术标签:

【中文标题】swift 3中只需要来自json的键(状态)和值(0)【英文标题】:need only key(Status) and value(0) from json in swift 3 【发布时间】:2017-07-01 15:18:57 【问题描述】:

"items": [

"startTime": "1498667581661",
"endTime": "1498667821661",
"dateTime": "2017-06-28T16:33:01.661Z",
"totalTime": "4",
"auctionName": "Bbbb",
"status": 1,
"id": "4760417733705728",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498772812087",
"endTime": "1498772992087",
"dateTime": "2017-06-29T21:46:52.087Z",
"totalTime": "3",
"auctionName": "sdasdasdd",
"status": 1,
"id": "5080491044634624",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498833895423",
"endTime": "1498834375423",
"dateTime": "2017-06-30T14:44:55.423Z",
"totalTime": "8",
"auctionName": "Boston",
"status": 1,
"id": "5085211482128384",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498767894987",
"endTime": "1498768254987",
"dateTime": "2017-06-29T20:24:54.987Z",
"totalTime": "6",
"auctionName": "Dfddd",
"status": 0,
"id": "5111065843073024",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498640043323",
"endTime": "1498640283323",
"dateTime": "2017-06-28T08:54:03.323Z",
"totalTime": "4",
"auctionName": "Andsda",
"status": 1,
"id": "5118511437316096",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498807228606",
"endTime": "1498807348606",
"dateTime": "2017-06-30T07:20:28.606Z",
"totalTime": "2",
"auctionName": "Dxf",
"status": 1,
"id": "5146118144917504",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498806518484",
"endTime": "1498807358484",
"dateTime": "2017-06-30T07:08:38.484Z",
"totalTime": "14",
"auctionName": "rrrtttt",
"status": 1,
"id": "5151952589553664",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498807683483",
"endTime": "1498807863483",
"dateTime": "2017-06-30T07:28:03.483Z",
"totalTime": "3",
"auctionName": "wwew",
"status": 1,
"id": "5956451503702016",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498803576630",
"endTime": "1498803816630",
"dateTime": "2017-06-30T06:19:36.630Z",
"totalTime": "4",
"auctionName": "zzzz",
"status": 0,
"id": "5964732200648704",
"kind": "auctionTimeApi#resourcesItem"
,

"startTime": "1498833083854",
"endTime": "1498833563854",
"dateTime": "2017-06-30T14:31:23.854Z",
"totalTime": "8",
"auctionName": "Dartmouth",
"status": 0,
"id": "6314781967384576",
"kind": "auctionTimeApi#resourcesItem"

],
"kind": "auctionTimeApi#resources",
"etag": "\"l-71RhD3VMYkQ-s_W643oBlpkCw/1SZlmWzcSB8XxEnhJpjVvwPV5k4\""

以上是我在 Google 云中的 JSON 数据 添加这是我的 SWIFT3 代码:

import UIKit

class ViewController: UIViewController , UITableViewDataSource 



    @IBOutlet weak var auctionLabel: UILabel!

    @IBOutlet weak var auctionTableView: UITableView!


    var fetchAuctionName = [AuctionName]()

    override func viewDidLoad() 
        super.viewDidLoad()

        auctionTableView.dataSource = self

        parseData()
    

    override var prefersStatusBarHidden: Bool 
        return true
    

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

        return fetchAuctionName.count

    

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 

        let cell = auctionTableView.dequeueReusableCell(withIdentifier: "cell")

        cell?.textLabel?.text = fetchAuctionName[indexPath.row].auctionname
        cell?.detailTextLabel?.text = fetchAuctionName[indexPath.row].auctionname

        return cell!
    



    func parseData() 

        fetchAuctionName = []

        let url = "urll"
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request)  (data, response, error) in

            if (error != nil)
                print("Error")
            
            else


                do
                    let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary

                    let jsonArray = fetchData.value(forKey: "items") as! NSArray


                    for eachFetchedAuctionName in jsonArray 

                        let eachAuctionName = eachFetchedAuctionName as! [String : Any]

                        let auctionname = eachAuctionName["auctionName"] as! String

                        self.fetchAuctionName.append(AuctionName(auctionname: auctionname));

                    



                    self.auctionTableView.reloadData()



                
                catch
                    print("Error 2")
                
            

        
        task.resume()

    




class AuctionName: NSObject 

    var auctionname : String

    init(auctionname : String) 
        self.auctionname = auctionname

    

使用此代码,我可以打印 JSON 数据中的所有状态值

我的问题是;我只需要打印状态值为 0 的那些。如何修改我的代码来实现这一点?

【问题讨论】:

使用 nspredicate . 感谢您抽出宝贵时间.. 顺便说一句,我认为我们不需要 nspredicate。只要声明就足够了。任何方式感谢您的时间 【参考方案1】:

试试这个

     func parseData() 

            fetchAuctionName = []

            let url = "urlllll"
            var request = URLRequest(url: URL(string: url)!)
            request.httpMethod = "GET"

            let configuration = URLSessionConfiguration.default
            let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

            let task = session.dataTask(with: request)  (data, response, error) in

                if (error != nil)
                    print("Error")
                
                else

                       do
                        let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary

                        let jsonArray = fetchData.value(forKey: "items") as! NSArray


                        for eachFetchedAuctionName in jsonArray 

                       let eachAuctionName = eachFetchedAuctionName as! [String : Any]

              let auctionname = eachAuctionName["auctionName"] as! String
               if let status = eachAuctionName["staus"] as? Bool
                if status == true
                   self.fetchAuctionName.append(AuctionName(auctionname: auctionname));
                

                                 
    
                    self.auctionTableView.reloadData()
                
                catch
                    print("Error 2")
                
            

        
        task.resume()
    

【讨论】:

感谢您的重播.. 但我用这段代码解决了它并且它的工作。 if(eachAuctionName["status"] as! Int == 0) self.fetchAuctionName.append(AuctionName(auctionname:auctionname)); 【参考方案2】:
        for eachFetchedAuctionName in jsonArray 

         let eachAuctionName = eachFetchedAuctionName as! [String : Any]
         let auctionname = eachAuctionName["auctionName"] as! String
        self.fetchAuctionName.append(AuctionName(auctionname: auctionname));

    // you can typecast to either String or an Int and then compare it respectively 
   //with a String "1" or an Int(1), whichever suits your app


        guard let status = eachAuctionName["status"] as! Int else  return 
            if status == 0 
                print("0 found")
              
        

一个建议:使用 swift 4 Decodable 协议,将 JSON 轻松解析为您选择的结构或类的自定义对象,使代码看起来干净整洁。

【讨论】:

条件绑定的初始化程序必须有可选类型而不是'字符串' 我收到了这个错误!!! 感谢您的重播.. 但我用这段代码解决了它并且它的工作。 if(eachAuctionName["status"] as! Int == 0) self.fetchAuctionName.append(AuctionName(auctionname:auctionname)); 是的,正如我所说,这取决于您的应用程序如何解析它,无论是字符串还是整数,我会更新我的答案,请接受它。

以上是关于swift 3中只需要来自json的键(状态)和值(0)的主要内容,如果未能解决你的问题,请参考以下文章

Swift:字典,删除零的键和值

在spring boot中仅获取值而不是JSON响应中的键和值

Json - 扁平化 Hive 中的键和值

需要使用 Objective C 将新的键和值添加到 Plist 中? [复制]

Json 中的键和值

将json对象值变成javascript中的键和值[关闭]