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

时间:2018-10-25 10:02:41

标签: swift api alamofire

我是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;
        }
    );
}

无法理解我要去哪里哪里,请帮助我解决此问题。

print(result)的输出

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

1 个答案:

答案 0 :(得分:0)

两个问题:

  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
...