如何在没有任何第三方库的情况下使用Alamofire在Swift 3.0中parsingJSON

在这里我想通过urlparsingJSON。 这是在url上可用的实际JSON数据。 所以我需要parsing它,并阅读我的应用程序使用Alamofire。 但我无法做到这一点。

JSON数据在我的url。

{ "main": [ { "date": "2017-01-11", "USDARS": "15.8302", "USDCLP": "670.400024", "USDSDG": "6.407695" }, { "date": "2017-01-12", "USDARS": "15.804999", "USDCLP": "661.599976", "USDSDG": "6.407697" }, { "date": "2017-01-13", "USDARS": "15.839041", "USDCLP": "659.200012", "USDSDG": "6.407704" }, { "date": "2017-01-14", "USDARS": "15.839041", "USDCLP": "659.200012", "USDSDG": "6.407704" } ] } 

我如何在3.0版本中使用Alamofire来读取它

下面是实际上我试图parsingJSON数据通过url。

 Alamofire.request("myurl") .responseJSON { response in print("In Alamofire") if let arr = response.result.value as? [String:AnyObject] { if let arr = response.result.value as? [NSDictionary] { let val1 = (arr["main"]["USDARS"] as? String) print(val1) //It does not print any thing. } } } 

请帮帮我。 我是新来的。

顶级json是[String:Any] ,main是一个数组,即[[String:String]]

  Alamofire.request("myurl") .responseJSON { response in if let result = response.result.value as? [String:Any], let main = result["main"] as? [[String:String]]{ // main[0]["USDARS"] or use main.first?["USDARS"] for first index or loop through array for obj in main{ print(obj["USDARS"]) print(obj["date"]) } } } 

你应该使用SwiftyJson ,这是一个jsonparsing库,对于Alamofire非常有用

在你的情况下,你可以用swiftyJson做这样的事情:

 //Array & Dictionary var jsonArray: JSON = [ "main": ["date": "2017-01-11", "USDARS": "15.8302"] ] let dateString = jsonArray["main"][0]["date"].string print(dateString) = "2017-01-11" 
  @IBAction func btnget(_ sender: UIButton) { let urlpath : String = "http://202.131.123.211/UdgamApi_v4/App_Services/UdgamService.asmx/GetAllTeacherData?StudentId=2011111" let url = URL(string: urlpath) var urlrequest = URLRequest(url: url!) urlrequest.httpMethod = "GET" let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: urlrequest) { (data, response, error) in do { guard let getResponseDic = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] else { print("error trying to convert data to JSON") return } // now we have the todo, let's just print it to prove we can access it print(getResponseDic as NSDictionary) let dic = getResponseDic as NSDictionary let msg = dic.object(forKey: "message") print(dic) //let arrObj = dic.object(forKey: "teacherDetail") as! NSArray //print(arrObj) //let arr = dic.value(forKey: "TeacherName")as! NSArray print(((dic.value(forKey: "teacherDetail") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "TeacherName") as! String) // the todo object is a dictionary // so we just access the title using the "title" key // so check for a title and print it if we have one // print("The title is: " + todoTitle) } catch { print("error trying to convert data to JSON") return } } task.resume() }