Parsing json data using Codable

匆匆过客 提交于 2020-01-30 11:31:28

问题


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()
}

回答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"])


来源:https://stackoverflow.com/questions/58676310/parsing-json-data-using-codable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!