gpt4 book ai didi

ios - 使用 Codable 解析 json 数据

转载 作者:行者123 更新时间:2023-11-30 10:26:59 25 4
gpt4 key购买 nike

我刚开始使用 Codable 解析 JSON 数据,但我的 JSON 格式遇到了问题。我无法将正确的字段解析到我的 Employee 对象中。这是我第一次使用可编码并处理复杂的 URL。这就是我的 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"
}
]
}

这是我的代码:

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

最佳答案

替换

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

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

关于ios - 使用 Codable 解析 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59971752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com