Search code examples
iosjsonswiftget

How to Display Json Response using get method


Here is my Response and I want to print the response using array I want to take some details in the response like "Id" and "available" and "leaves" and I have to show in a label in my VC

{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0

}

my code is

struct jsonstruct8:Decodable  {

var available: String
var leaves: String

}

var arrdata = [jsonstruct8]()


func getdata(){
    let url = URL(string: "MY URL")
    URLSession.shared.dataTask(with: url!) { (data, response, error )in
        do{if error == nil{

            self.arrdata = try JSONDecoder().decode([jsonstruct8].self, from: data!)

            for mainarr in self.arrdata{
            print(mainarr.available,":",mainarr.leaves)
            print(data)
            }
            }

        }catch{
            print("Error in get json data")
        }

        }.resume()
}

I am getting "Error in get json data"


Solution

  • Sample JSON:

      {
        "id": 1,
        "emp_id": "001",
        "termination_date": "active",
        "blood_group": "A+",
        "rating": 0,
        "noOfStars": 0,
        "starOfMonth": false,
        "gender": "Female",
        "expertise": "",
        "experience": "",
        "leaves": 0,
        "available": 5,
        "compoff": 0,
        "earnedLeaves": null,
        "wfh": 0
      }
    

    Model:

    struct Employee: Codable {
        let id: Int
        let empId: String
        let terminationDate: String
        let available: Int
        let leaves: Int
        //add other properties as well....
    }
    

    Parsing:

    if let data = data {
        if let data = data {
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                var employee = try JSONDecoder().decode(Employee.self, from: data)
                print("\(employee.available) : \(employee.leaves)") //here you can modify then employee details...
            } catch  {
                print(error)
            }
        }
    }
    

    Edit:

    Always update the UI on main thread.

    DispatchQueue.main.async {
        self.totalLeaves.text = "\(employee.leaves)"
    }