0

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"

8
  • The JSON you've added is not an array. Add the whole valid JSON here. Commented Jun 27, 2019 at 5:43
  • Also, add the Codable model that you're using. Commented Jun 27, 2019 at 5:44
  • "I am getting "Error in get json data", that's because you have hard coded that error message. Do print(error) instead so that you get the real error printend Commented Jun 27, 2019 at 6:01
  • @ PGDev I have Updated my Question please check Commented Jun 27, 2019 at 6:01
  • This is the error I am getting. typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil)) Commented Jun 27, 2019 at 6:04

1 Answer 1

1

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)"
}
Sign up to request clarification or add additional context in comments.

8 Comments

I am getting this compile error . Value of type 'JSONDecoder' has no member 'keyDecodingStrategy'
my response is starting with an object not with an array sorry I forgot to mention
Updated the answer for object instead of array.
I am trying your code but getting this compile error "Value of type 'JSONDecoder' has no member 'keyDecodingStrategy' " for this line code decoder.keyDecodingStrategy = .convertFromSnakeCase. I am using swift 4 Xcode 9.2
yes I figured that and help me how to assign that parameters (Int )value to UILabel I am unable to assign it
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.