swift json how to fill an object

时间:2017-04-22 06:36:02

标签: json swift

here is my issue, I would like to create a function with this prototype :

func doPostRequest(......)->JSON()

And I write it like that :

func downloadData(completed:@escaping()->()){
    Alamofire.request(url).responseJSON(completionHandler: {
        response in
        let result = response.result

        if let dict = ... {

            self._temp = String(format: "%.0f °C", temp - 273.15)
            ...
        }

        completed()
    })
}

I'd like to return an Any object or dictionary, something with my JSON in... but each time I try to implement return I have a nil object ! Maybe a scope problem how can I implement this function to have

var myJson:NSDictionary
myJson=downloadData(......) ???

Thanks for your help

2 个答案:

答案 0 :(得分:0)

由于正文中的方法异步工作,您必须使用完成处理程序声明您的请求方法,例如

func doPostRequest(completion: @escaping ([String:Any])->())

返回时,它会传递一个Swift词典。

该方法可与此代码一起使用:

var myJson = [String:Any]()

...

doPostRequest() { json in 
  self.myJson = json
  // do something with the returned data
}

答案 1 :(得分:0)

首先,您需要创建一个ObjectMapper来映射您的对象并使用AlamofireObjectMapper来获取  试试这段代码

protected function getDateFormat()
{
 return 'U';
}