Json 在Swift中访问嵌套数据
我正在访问一个API并将json响应解码为一个用户对象,但我正在尝试更改json API结构。如果我使用以下代码返回一个基本JSON对象Json 在Swift中访问嵌套数据,json,swift,decode,Json,Swift,Decode,我正在访问一个API并将json响应解码为一个用户对象,但我正在尝试更改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 l
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你可以试试
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
}
或 你可以试试
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
}
或
您的
Codable
User
对象看起来像什么?而且。。。这些“嵌套对象集”是什么?您的Codable
User
对象看起来像什么?而且。。。这些“嵌套对象集”是什么?非常感谢。我有很多东西要学,但这解决了我的问题。非常感谢。我有很多东西要学,但这解决了我的问题。
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)
}