[英]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.我是使用 Codable 从 JSON 解析数据的新手,我的 JSON 的格式有问题。 I am not able to parse the correct fields into my Employee object.
我无法将正确的字段解析到我的员工 object 中。 This is my first time using codable and dealing with a complex URL.
这是我第一次使用可编码并处理复杂的 URL。 This is how my JSON url is structured: https://ibb.co/WgDNMNT
这就是我的 JSON url 的结构: 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"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.