访问 Swift 中的嵌套数据

Access Nested Data in Swift

我正在访问 API 并将 json 响应解码为用户对象,但我试图更改 JSON API 结构。如果我 return 使用此代码

的基本 JSON 对象
let httpURL = "https://dev.test/api/user"

var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            guard let data = data else {return}

            do {
                let user = try JSONDecoder().decode(User.self, from: data)

                DispatchQueue.main.async {
                    print(user.email)
                }
            } catch let jsonErr {
                print(jsonErr)
            }
        }
        task.resume()

及以下JSON

{
    "id": 2,
    "email": "test@example.com",
}

这很好用,但我想将 API 更改为 return 一组嵌套对象。例如

{
  "data": {
    "user": {
      "id": 2,
      "email": "test@example.com"
    },
    "notifications": [
      {
        "id": "123",
        "notifiable_type": "App\User"
      }
    ]
  }
}

如何解码用户?我已经尝试了这个 let user = try JSONDecoder().decode(User.self, from: data.data.user)let user = try JSONDecoder().decode(User.self, from: data["data"]["user"])

的几种变体

BT

你可以试试

struct Root: Codable {
    let data: DataClass
}

struct DataClass: Codable {
    let user: User
    let notifications: [Notification]
}

struct Notification: Codable {
    let id, notifiableType: String

    enum CodingKeys: String, CodingKey {
        case id
        case notifiableType = "notifiable_type"
    }
}

struct User: Codable {
    let id: Int
    let email: String
}

let user = try JSONDecoder().decode(Root.self, from:data)

do {

    let con = try JSONSerialization.jsonObject(with:data, options: [:]) as! [String:Any]
    let data = con["data"] as! [String:Any]
    let user = data["user"] as! [String:Any]
    let finData = try JSONSerialization.data(withJSONObject:user, options: [:])
    let userCon = try JSONDecoder().decode(User.self, from:finData) 
    print(userCon)

}
catch {

    print(error)
}