简体   繁体   中英

Parsing json data using Codable

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": "jm99@jfgj.com",
      "biography": "student of arts"
    },
    {
      "uuid": "0djkdjjf734783749c",
      "full_name": "Joe Morris",
      "phone_number": "44445399",
      "email_address": "jm99@jfgj.com",
      "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()
}

Replace

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

With

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM