gpt4 book ai didi

swift - 在标签中打印 JSON 响应时出现问题

转载 作者:行者123 更新时间:2023-11-30 11:03:41 25 4
gpt4 key购买 nike

我是 swift 新手,我正在使用 alamofire 方法调用 API。我成功收到响应,但无法理解如何解析标签,这是我尝试过的代码

Alamofire.request(url, method: .get).responseJSON
{
response in
let result = response.result.value
print(response)
if result != nil{
let data = result as! [String : AnyObject]


let userdata = data["data"] as! NSDictionary

let address = userdata["address"]
let city = userdata["city"]
let pincode = userdata["pincode"]
let state = userdata["state"]
self.lblAddress.text = city as? String
self.lblCity.text = address as? String
self.lblpincode.text = pincode as? String
self.lblstate.text = state as? String
}
}

这是我收到的回复

SUCCESS: {
"city_address" =
(
{
address = "404 palladium business hub.";
city = Ahmedabad;
pincode = 380061;
state = Gujarat;
}
);
}

无法理解我哪里出了问题,请帮助我解决这个问题。

输出打印(结果)

{
"city_address" = (
{
address = "404 palladium business hub.";
city = Ahmedabad;
pincode = 380061;
state = Gujarat;
}
);
}

最佳答案

两个问题:

  1. 包含地址信息的对象是键city_address的值
  2. 这个对象显然是一个数组(注意括号)

并且不要在 Swift 中使用 NSDictionary ,并且未指定的 JSON 值始终为 Any

if let result = response.result.value as? [String:Any], 
let dataArray = result["city_address"] as? [[String : Any]], // maybe even `[[String:String]]`
let userData = dataArray.first {
let address = userData["address"]
let city = userData["city"]
let pincode = userData["pincode"]
let state = userData["state"]
DispatchQueue.main.async {
self.lblAddress.text = address as? String
...

关于swift - 在标签中打印 JSON 响应时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52986555/

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