从 swift api 调用中获取 JSON 响应

Get the JSON response from swift api call

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

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

我尝试了几种方法来从中得到 "token"。

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

但是其中 none 行得通。谁能帮我 ?这是 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)
}