我正在访问一个API并将json响应解码为一个User对象,但是我试图更改JSON API结构。如果我使用此代码返回基本的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以返回一组嵌套对象。例如
{
"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
答案 0 :(得分:2)
您可以尝试
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)
OR
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)
}