Home > Software design >  how to extract a single json object into a separate array?
how to extract a single json object into a separate array?

Time:08-01

File JSON with data

{
    "city_is_regional" = 0;
    id = 19;
    "id_locale" = 19;
    lang = 1;
    "last_edit_time" = 1494940557;
    name = "\U0428\U043a\U043b\U043e\U045e";
    region = "Mogilev region";
    visible = 1;
},
{
    "city_is_regional" = 0;
    id = 93;
    "id_locale" = 367;
    lang = 1;
    "last_edit_time" = 1644925878;
    name = "\U0428\U0447\U0443\U0447\U044b\U043d";
    region = "Grodno region";
    visible = 1;
}

how to extract an elements name and id individually? I just know how to display the whole date in full, but I have no idea individually

func parseJSON() {
    let urlString = "https://krokapp.by/api/get_cities/11/"
    AF.request(urlString).responseJSON { responce in
        switch responce.result {
        case .success:
            if let jsonData = try? JSONDecoder().decode([City].self, from: responce.data!){
             print(jsonData)
            } else{
                print("error")
            }
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}
    

CodePudding user response:

Here is an example how you do that

class YourViewController:UIViewController, UITableViewDataSource,UITableViewDelegate {

    let tableView = UITableView()
    
    var cities:[City] = [] {
        didSet {
            tableView.reloadData() // reload when cities is available

        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        parseJSON { cities, error in
            if let cities = cities { // if cities is get without any error
                self.cities = cities
            }
        }
    }
    
    func parseJSON(completion: @escaping (_ cities:[City]?, _ error:Error?) -> Void) {
           let urlString = "https://krokapp.by/api/get_cities/11/"
        completion(nil,nil)
           AF.request(urlString).responseJSON { responce in
               switch responce.result {
               case .success:
                   if let jsonData = try? JSONDecoder().decode([City].self, from: responce.data!){
                    completion(jsonData,nil)
                   } else{
                     completion(nil, error)
                   }
               case .failure(let error):
                   print(error.localizedDescription)
                   completion(nil, error)
               }
           }
       }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cities.count // all cities in table
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CityCell.id) as! CityCell
        cell.titleLabel.text = cities[indexPath.row].name // just showing name in titleLable
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(cities[indexPath.row]) // this will print that object you tapped 
    }
    

}

the custom cell class of

class CityCell:UITableViewCell {
    
    static let id = "CityCell"
    
    let titleLabel:UILabel = {
        let label = UILabel()
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(titleLabel)
        titleLabel.frame = frame
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

this how you get data of single object/ city

class YourController:UIViewController,UITableViewDelegate {
    var cities:[City] = []
    
    var singleObjec:City? {
        didSet {
            print(singleObjec)
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        singleObjec = cities[indexPath.row]
    }
}

CodePudding user response:

You need to create a model class first.

class CityModel {
    var city_is_regional: String?
    var id: Int?
    var id_locale: Int?
    var lang: Int?
    var last_edit_time: Long?
    var name: String?
    var region: String?
    var visible: Int?
}

and then you can get.

JSONArray jsonMainArr = new JSONArray("json String");
//now just loop the json Array
for (var i = 0; i < jsonMainArr.length;   i) {                     
    var jsonData: JSONObject = jsonMainArr.getJSONObject(i);                     
    // Decode
    let jsonDecoder = JSONDecoder()
    let cityObject = try jsonDecoder.decode(CityModel.self, from: jsonData)        
}
  • Related