получить значения JSON в зависимости от конкретного дочернего значения - PullRequest
1 голос
/ 11 апреля 2019

как я могу получить значения в зависимости от значения в дочернем узле.Например, если у меня есть JSON, как это

      {
          "id": 14,
          "name": "АBC",
          "picture": 44,
          "group": {
              "id": 2,
              "gname": "AAA",
              "pic": 1
          }
     },
      {
          "id": 14,
          "name": "АBC",
          "picture": 44,
          "group": {
              "id": 1,
              "gname": "BB",
              "pic": 2
          }
      }...
]

я хочу получить список всех имен, где дочернее значение равно "AAA"

Я знаю, как прочитать все значения для имени, но я не знаюне знаю, как их читать, если мне нужны только имена, которые имеют конкретное значение gname.

Вот код:

import UIKit
import Alamofire
import SwiftyJSON

class ThirdViewController : UITableViewController {

    var dataInfo = [[String: AnyObject]]()
    let url = "http://XXX"
    let header = ["X": "XXX"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.rowHeight = 50
        getData(url: url)
        self.tableView.reloadData()
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataInfo.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! Cell2
        cell.lblName?.text = dataInfo[indexPath.row]["name"] as? String
        return cell
    }
    func getData(url: String) {
        Alamofire.request(url, method: .get, headers: header)
            .responseJSON { response in
                if response.result.isSuccess {
                    print("Sucess! Got the data")
                    let dataJSON : JSON = JSON(response.result.value!)
                    self.updateData(json: dataJSON)

                } else {
                    print("Error: \(String(describing: response.result.error))")
                }
        }
        self.tableView.reloadData()
    }
    func updateData(json : JSON) {
        if let data = json[].arrayObject {
            self.dataInfo = data as! [[String: AnyObject]]
            self.tableView.reloadData()
        }
        else {
            print("cannot connect to the server")
        }
    }

}

Буду признателен, если кто-нибудь сможет мне помочь.

1 Ответ

0 голосов
/ 12 апреля 2019

Сначала вы должны использовать Codable вместо SwiftyJSON

Итак, вы должны добавить эти модели

struct Group: Codable {
    var id: Int?
    var gname: String?
    var pic: Int?

    enum CodingKeys: String, CodingKey {
        case id, gname, pic
    }
}

struct User: Codable {
    var id: Int?
    var name: String?
    var picture: Int?
    var group: Group?

    enum CodingKeys: String, CodingKey {
        case id, name, picture, group
    }
}

И теперь вы должны добавить это к Alamofire.request

let jsonDecoder = JSONDecoder()

let dataJSON = try? jsonDecoder.decode([User].self, from: response.data!)

Теперь для фильтра Thing, если вам нужен только элемент с "AAA", мы можем отфильтровать массив как

let users: [User] = []

let searchString = "AAA"

let filterResults = users.filter({
    $0.group.filter({$0.gname == searchString}).count > 1
})

Так что весь ваш код будет выглядеть как

class ThirdViewController : UITableViewController {

    var dataInfo: [User] = []

    let url = "http://XXX"
    let header = ["X": "XXX"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = 50

        getData(url: url)
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataInfo.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! Cell2
        cell.lblName?.text = dataInfo[indexPath.row].name
        return cell
    }

    func getData(url: String) {
        Alamofire.request(url, method: .get, headers: header)
            .responseJSON { response in
                if response.result.isSuccess {
                    print("Sucess! Got the data")

                    guard let responseData = response.data else {
                      print("didn't get any data from API")
                      return
                    }

                    let jsonDecoder = JSONDecoder()
                    let dataJSON = try? jsonDecoder.decode([User].self, from: responseData)

                    // Search data
                    let searchString = "AAA"

                    let filterResults = users.filter({
                        $0.group.gname == searchString
                    })

                    self.dataInfo = filterResults

                    // Reload Data
                    self.tableView.reloadData()
                } else {
                    print("Error: \(String(describing: response.result.error))")
                }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...