ios - 使用结构在 Swift 5 中使用 JSONDecoder 解析 JSON

标签 ios json swift parsing jsondecoder

我从 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/

相关文章:

ios - 具有输入和输出一维数据缓冲区的 Metal 计算着色器?

java - 如何在 Rest 中从 JSON 对象中单独获取数组

java - 通过 Jackson ObjectMapper 将参数化 url 反序列化为 java.net.URI 时出现 InvalidFormatException

ios - 无法在 iOS Swift 中使用 Assets 运行动画

iphone - 如何为 iOS 设计师绘制蓝图?

ios - 无法将 Firebase 导入 Swift 类

javascript - 错误: AJAX call within AJAX response

swift - 如何将字符串转换为json字典?

ios - 如何在 iOS 中使用现有的 SQLite 数据库?

ios - 如何使用AFNetworking将nsdata下载到内存