Swift ios解析json数据只获取选定的数据

时间:2018-04-26 06:39:18

标签: ios swift parsing

下面是我试图提取JSON对象的代码。我只想要状态数据!=静态并在tableView

中显示
postman response
[
    {
        "id": 249,
        "name": "aBrush your teeth",
        "desc": "Brush your teeth",
        "reward": "1.00",
        "sched": "2015-01-01T08:00:00+08:00",
        "parent": "",
        "type": "",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "static"
        },
        "date_created": "2018-04-25T14:27:20.405928+08:00",
        "date_modified": "2018-04-26T11:56:02.030647+08:00"
    },
    {
        "id": 250,
        "name": "Brush your teeth",
        "desc": "Brush your teeth",
        "reward": "1.00",
        "sched": "2015-01-01T08:00:00+08:00",
        "parent": "",
        "type": "",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "static"
        },
        "date_created": "2018-04-25T14:28:49.780354+08:00",
        "date_modified": "2018-04-26T11:56:05.616333+08:00"
    },
    {
        "id": 252,
        "name": "Brush your teeth",
        "desc": "Brush your teeth",
        "reward": "1.00",
        "sched": "2015-01-01T08:00:00+08:00",
        "parent": "",
        "type": "",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "static"
        },
        "date_created": "2018-04-25T14:31:02.274405+08:00",
        "date_modified": "2018-04-26T11:59:57.676148+08:00"
    },
    {
        "id": 253,
        "name": "Brush your teeth",
        "desc": "Brush your teeth",
        "reward": "1.00",
        "sched": "2015-01-01T08:00:00+08:00",
        "parent": "",
        "type": "",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "static"
        },
        "date_created": "2018-04-25T14:34:37.097498+08:00",
        "date_modified": "2018-04-26T09:42:24.633359+08:00"
    },
    {
        "id": 254,
        "name": "Brush your teeth",
        "desc": "Brush your teeths",
        "reward": "1.00",
        "sched": "2015-01-01T08:00:00+08:00",
        "parent": "",
        "type": "",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "static"
        },
        "date_created": "2018-04-25T14:36:53.766088+08:00",
        "date_modified": "2018-04-26T11:56:15.757769+08:00"
    },
    {
        "id": 260,
        "name": "chorename",
        "desc": "{\n  \"questions\" : [\n    {\n      \"b\" : 2,\n      \"a\" : 1\n    },\n    {\n      \"b\" : 3,\n      \"a\" : 2\n    },\n    {\n      \"b\" : 2,\n      \"a\" : 8\n    },\n    {\n      \"b\" : 9,\n      \"a\" : 7\n    },\n    {\n      \"b\" : 3,\n      \"a\" : 6\n    }\n  ],\n  \"operation\" : \"+\"\n}",
        "reward": "1.00",
        "sched": "2018-04-19T15:54:24.657644+08:00",
        "parent": "shit",
        "type": "homework",
        "child": "",
        "occurrence": {
            "name": "once"
        },
        "status": {
            "name": "ongoing"
        },
        "date_created": "2018-04-26T10:13:42.913149+08:00",
        "date_modified": "2018-04-26T10:13:42.953485+08:00"
    }
]

获取数据的代码            //这里我只想从dapi获取数据的状态名称!=“static”         并将它附加到getalldetail这是一个var getAllDetail:[[String:Any]] = [String:Any]

func demoApi() {
            Alamofire.request("test.api", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

                switch(response.result) {

                case .success(_):
                    guard let json = response.result.value as! [[String:Any]]? else{ return}

                    print("Api Response : \(json)")

                    // here i only want to get data from the dapi which status name != "static"
                    for item in json {

                        self.getAllDetail.append(item)


                    }
                    if !self.getAllDetail.isEmpty{
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                    break

                case .failure(_):
                    print("Error")
                    break

                }
            }

        }

2 个答案:

答案 0 :(得分:2)

只需将filter应用于您的回复,如下所示。

let filtered  = json.filter { (dict) -> Bool in
       guard let status : [String : String] = dict["status"] as? [String : String], let statusString = status["name"] else {
         return false
       }
      return statusString.compare("static") != .orderedSame
    }

答案 1 :(得分:0)

我建议利用Swift 4的Codable协议并将JSON解码为结构体。这使得过滤数据变得非常容易。无需任何类型转换,无需订阅密钥。

  1. 创建结构

    struct ResponseData : Decodable {
        let id: Int
        let name, desc, reward : String
        let sched, parent, type, child : String
        let occurrence : Status
        let status : Status
        let dateCreated, dateModified : String
    }
    
    struct Status : Decodable {
        let name : String
    }
    
  2. 您的数据源数组getAllDetail必须声明为

    var getAllDetail = [ResponseData]()
    
  3. Alamofire完成处理程序中获取data并使用JSONDecoder将JSON解码为结构。这些项目可以使用filter{ $0.status.name == "static" }

    进行过滤 - 非常具有描述性
    Alamofire.request("test.api", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
    
          switch(response.result) {
    
          case .success:
              guard let data = response.data else { return }
    
              let decoder = JSONDecoder()
              decoder.keyDecodingStrategy = .convertFromSnakeCase
              let result = try decoder.decode([ResponseData].self, from: data)
              self.getAllDetail = result.filter{ $0.status.name == "static" }
    
              DispatchQueue.main.async {
                  self.tableView.reloadData()
              }
    
         case .failure(let error):
             print("Error", error)
         }
     }