0

I am new to using Codable for parsing data from JSON and I am having trouble with the format of my JSON. I am not able to parse the correct fields into my Employee object. This is my first time using codable and dealing with a complex URL. This is how my JSON url is structured: https://ibb.co/WgDNMNT

{
  "students": [
    {
      "uuid": "0djkdjjf734783749c",
      "full_name": "Joe Morris",
      "phone_number": "44445399",
      "email_address": "[email protected]",
      "biography": "student of arts"
    },
    {
      "uuid": "0djkdjjf734783749c",
      "full_name": "Joe Morris",
      "phone_number": "44445399",
      "email_address": "[email protected]",
      "biography": "student of arts"
    }
  ]
}

Here is my code:

struct Students: Codable {
    var uuid: String?
    var fullName: String?
    var phoneNumber: String?
    var emailAddress: String?
    var biography: String?

}
//Custom Keys
enum CodingKeys: String, CodingKey{
    case uuid
    case fullname = "full_name"
    case phoneNumber = "phone_number"
    case emailAddress = "email_address"
    case biography = "biography"
}


func parseData(){
    guard let url = URL(string: "xxxxxxxxxx") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let dataResponse = data,
            error == nil else {
                print(error?.localizedDescription ?? "Error")
                return }
        do{
            let decoder = JSONDecoder()
            let model = try decoder.decode([Students].self, from: dataResponse)

        } catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}
1
  • You are missing the outer students: object. You are trying to parse the array directly. Commented Nov 3, 2019 at 0:03

1 Answer 1

1

Replace

let model = try decoder.decode([Students].self, from: dataResponse)

With

let model = try decoder.decode([String:[Students]].self, from: dataResponse)
print(model["students"])
Sign up to request clarification or add additional context in comments.

Comments

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.