且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Alamofire和解码获取JSON-Swift 4

更新时间:2021-12-20 00:23:45

id 不在该级别上在您期望的地方。这就是错误消息指出的内容。

id name 在(sub )的键响应的字典。

The key id is not on the level where you expect it. That's what the error message states.
The keys id and name are in the (sub)dictionary for key response.

因此您需要一个伞形结构

So you need an umbrella struct

struct Root : Decodable {
   let status: String
   let response: User
}

struct User: Decodable {
    let id: String
    let name: String
}

然后解码

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