我从 Rest API 获取 json 格式的结果。现在我想用 JSONDecoder 解析这个 JSON,但我并不真正理解我的响应的结构。
为此,我已经尝试创建结构来获取“FirstUser”的“名称”。
{
"User":[
{
"FirstUser":{
"name":"John"
},
"Information":"XY",
"SecondUser":{
"name":"Tom"
}
最佳答案
JSON
{
"User":[
{
"FirstUser":{
"name":"John"
},
"Information":"XY",
"SecondUser":{
"name":"Tom"
}
}
]
}
型号
// MARK: - Empty
struct Root: Codable {
let user: [User]
enum CodingKeys: String, CodingKey {
case user = "User"
}
}
// MARK: - User
struct User: Codable {
let firstUser: FirstUserClass
let information: String
let secondUser: FirstUserClass
enum CodingKeys: String, CodingKey {
case firstUser = "FirstUser"
case information = "Information"
case secondUser = "SecondUser"
}
}
// MARK: - FirstUserClass
struct FirstUserClass: Codable {
let name: String
}
解析
do {
let res = try JSONDecoder().decode(Root.self, from: data)
print(res.first?.firstUser.name)
} catch {
print(error)
}
关于ios - 使用结构在 Swift 5 中使用 JSONDecoder 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723197/