如何在Swift中获取JSON数据并将其添加到URL

我如何获取JSON数据并将其添加到URL?

我的情况是我会访问JSON的URL,但我需要从其他JSON的URL值。

这是我的Json,我需要一个令牌来访问它。 https://api-sandbox.tiket.com/flight_api/all_airport/token= ……

要获取令牌,我必须从其他JSON访问,这个视图的另一个JSON来获取令牌。

{“diagnostic”:{“status”:200,“elapsetime”:“0.2082”,“memoryusage”:“16.99MB”,“unix_timestamp”:1499832598,“confirm”:“success”,“lang” ,“currency”:“IDR”},“output_type”:“json”,“login_status”:“false”,“token”:“ b650fce732668b58b0a4c404b65932e972ad123d ”}

我必须获取价值标记,并将其添加到第一个JSON URL来访问第一个JSON

这我的编码:

func getLatestKotaTujuan(){

var tujuanUrl = URLComponents(string: "https://api-sandbox.tiket.com/flight_api/all_airport?")! tujuanUrl.queryItems = [ URLQueryItem(name: "token", value: "4d4bba355bb920fbdc1aa3848769a59ba74ea03c" ), URLQueryItem(name: "output", value: "json") ] let request = tujuanUrl.url let task = URLSession.shared.dataTask(with: request!, completionHandler: { (data, response, error) -> Void in if let error = error { print(error) return } // Parse JSON data if let data = data { self.kotaTujuan = self.parseJsonData(data: data) // Reload table view OperationQueue.main.addOperation({ self.tableView.reloadData() }) } }) task.resume() } 

你可以使用Alamofire&SwiftyJSON

  1. 安装两个cocopod

      pod 'Alamofire' pod 'SwiftyJSON' 
  2. 我的Json看起来像

     {"loginNodes":[{"errorMessage":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]} 
  3. 声明multidimensional array

      var arrRes = [[String:AnyObject]]() 
  4. Alamofire从服务器获取JSON

      func getList() { Alamofire.request("url.....", method: .post, parameters: [ "userNameid":"25" ]).responseJSON{(responseData) -> Void in if((responseData.result.value != nil)){ // let jsonData = JSON(responseData.result.value) HUD.hide(); if((responseData.result.value != nil)){ let swiftyJsonVar = JSON(responseData.result.value!) if let resData = swiftyJsonVar["loginNodes"].arrayObject { self.arrRes = resData as! [[String:AnyObject]] } if self.arrRes.count > 0 { self.tableView.reloadData() } } } } } 
  5. 使用like将数据设置为表格视图

      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrRes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Agent_Account_Balance_Cell cell.namelabel.text = arrRes[indexPath.row]["name"] as? String return cell }