gpt4 book ai didi

ios - 如何在 Swift4 中访问 JSON 响应中的特定数据

转载 作者:行者123 更新时间:2023-11-28 13:34:10 25 4
gpt4 key购买 nike

这是我收到响应的代码,我想在其中使用一些值我是这样写的,但是错误来了

let id = json["emp_id"] as! [String:Any]
let parameters = [
"email": empEm,
"password":"1234"
] as [String : Any]
guard let url = URL(string: "http://localhost:8080/company/employee/login") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody


let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}

if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
let id = json["emp_id"] as! [String:Any]


} catch {
print(error)
}
}

}.resume()

我的回答是

{
available = 3;
compoff = 0;
displayname = Vamsi;
"emp_id" = 001;
gender = Male;
id = 1;
leaves = 4;
rating = 0;
star = 0;
"termination_date" = active;
wfh = 0;
}

我想从响应中获取 id、emp_id 等详细信息

最佳答案

您需要像这样解码您的 JSON:

let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]

JSONSerialization.jsonObject的返回值为Any,所以需要具体告诉编译器这个JSON代表的是什么对象。在你的情况下它是一个字典,所以使用 [String: Any]

关于ios - 如何在 Swift4 中访问 JSON 响应中的特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56898886/

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