gpt4 book ai didi

ios - 从 swift api 调用获取 JSON 响应

转载 作者:行者123 更新时间:2023-11-28 10:27:22 24 4
gpt4 key购买 nike

我对使用 iOS 进行快速编程有点陌生。谁能帮我解决以下问题。我收到如下 JSON 响应。

{
"response": {
"token": "d1fb8c33e401809691699fc3fa7dcb9b728dd50c7c4e7f34b909"
},
"messages": [
{
"code": "0",
"message": "OK"
}
]
}

我尝试了几种方法来从中获取“ token ”。

let data = json["response"] as! [[String : AnyObject]]

但是这些都不起作用。谁能帮我 ?这是 swift 3

最佳答案

因为 response 是一个有 token 的 json 对象,所以你需要将 response 转换为 dictionary 然后访问token 如下所示,

if let response = json["response"] as? [String : Any],
let token = response["token"] as? String {
print(token)
}

避免使用可能导致崩溃的强制展开。


在 Swift 中推荐的解析方式是使用 Codable。这是完整的示例,

// MARK: - Result
struct Result: Codable {
let response: Response
let messages: [Message]
}

// MARK: - Message
struct Message: Codable {
let code, message: String
}

// MARK: - Response
struct Response: Codable {
let token: String
}

do {
let data = Data() // Change this to data from the API
let result = try JSONDecoder().decode(Result.self, from: data)
print(result.response.token)
} catch {
print(error)
}

关于ios - 从 swift api 调用获取 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com