【问题标题】:Parsing json data using Codable使用 Codable 解析 json 数据
【发布时间】:2019-11-02 23:55:11
【问题描述】:

我是使用 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()
}

【问题讨论】:

  • 您缺少外部 students: 对象。您正在尝试直接解析数组。

标签: ios swift codable


【解决方案1】:

替换

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多