How to parse JSON response from Alamofire API in Swift?

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that.

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON {     (request, response, JSON, error) in      println(JSON?) } 

回答1:

The answer for Swift 2.0 Alamofire 3.0 should actually look more like this:

Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseJSON { response in switch response.result {                 case .Success(let JSON):                     print("Success with JSON: \(JSON)")                      let response = JSON as! NSDictionary                      //example if there is an id                     let userId = response.objectForKey("id")!                  case .Failure(let error):                     print("Request failed with error: \(error)")                 }     } 

https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md

UPDATE for Alamofire 4.0 and Swift 3.0 :

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)             .responseJSON { response in                 print(response) //to get status code                 if let status = response.response?.statusCode {                     switch(status){                     case 201:                         print("example success")                     default:                         print("error with response status: \(status)")                     }                 } //to get JSON return value             if let result = response.result.value {                 let JSON = result as! NSDictionary                 print(JSON)             }          } 


回答2:

like above mention you can use SwiftyJSON library and get your values like i have done below

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON {     (request, response, data, error) in  var json = JSON(data: data!)         println(json)           println(json["productList"][1])                   } 

my json product list return from script

{ "productList" :[  {"productName" : "PIZZA","id" : "1","productRate" : "120.00","productDescription" : "PIZZA AT 120Rs","productImage" : "uploads\/pizza.jpeg"},  {"productName" : "BURGER","id" : "2","productRate" : "100.00","productDescription" : "BURGER AT Rs 100","productImage" : "uploads/Burgers.jpg"}       ] } 

output :

{   "productName" : "BURGER",   "id" : "2",   "productRate" : "100.00",   "productDescription" : "BURGER AT Rs 100",   "productImage" : "uploads/Burgers.jpg" } 


回答3:

I found the answer on GitHub for Swift2

https://github.com/Alamofire/Alamofire/issues/641

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])     .responseJSON { request, response, result in         switch result {         case .Success(let JSON):             print("Success with JSON: \(JSON)")          case .Failure(let data, let error):             print("Request failed with error: \(error)")              if let data = data {                 print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")             }         }     } 


回答4:

I'm neither a JSON expert nor a Swift expert, but the following is working for me. :) I have extracted the code from my current app, and only changed "MyLog to println", and indented with spaces to get it to show as a code block (hopefully I didn't break it).

func getServerCourseVersion(){      Alamofire.request(.GET,"\(PUBLIC_URL)/vtcver.php")         .responseJSON { (_,_, JSON, _) in           if let jsonResult = JSON as? Array> {             let courseName = jsonResult[0]["courseName"]             let courseVersion = jsonResult[0]["courseVersion"]             let courseZipFile = jsonResult[0]["courseZipFile"]              println("JSON:    courseName: \(courseName)")             println("JSON: courseVersion: \(courseVersion)")             println("JSON: courseZipFile: \(courseZipFile)")            }       } } 

Hope this helps.

Edit:

For reference, here is what my PHP Script returns:

[{"courseName": "Training Title","courseVersion": "1.01","courseZipFile": "101/files.zip"}] 


回答5:

Swift 3, Alamofire 4.4, and SwiftyJSON:

Alamofire.request(url, method: .get)   .responseJSON { response in       if response.data != nil {         let json = JSON(data: response.data!)         let name = json["people"][0]["name"].string         if name != nil {           print(name!)         }       }   } 

That will parse this JSON input:

{   people: [     { name: 'John' },     { name: 'Dave' }   ] } 


回答6:

swift 3

pod 'Alamofire', '~> 4.4' pod 'SwiftyJSON'  File json format: {     "codeAd": {         "dateExpire": "2017/12/11",         "codeRemoveAd":"1231243134"         } }  import Alamofire import SwiftyJSON     private func downloadJson() {         Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in             debugPrint(response)              if let json = response.data {                 let data = JSON(data: json)                 print("data\(data["codeAd"]["dateExpire"])")                 print("data\(data["codeAd"]["codeRemoveAd"])")             }         }     } 


回答7:

I found a way to convert the response.result.value (inside an Alamofire responseJSON closure) into JSON format that I use in my app.

I'm using Alamofire 3 and Swift 2.2.

Here's the code I used:

    Alamofire.request(.POST, requestString,                       parameters: parameters,                       encoding: .JSON,                       headers: headers).validate(statusCode: 200..


回答8:

I usually use Gloss library to serialize or deserialize JSON in iOS. For example, I have JSON that looks like this:

{"ABDC":[{"AB":"qwerty","CD":"uiop"}],[{"AB":"12334","CD":"asdf"}]} 

First, I model the JSON array in Gloss struct:

Struct Struct_Name: Decodable {    let IJ: String?    let KL: String?    init?(json: JSON){        self.IJ = "AB" 

And then in Alamofire responseJSON, I do this following thing:

Alamofire.request(url, method: .get, paramters: parametersURL).validate(contentType: ["application/json"]).responseJSON{ response in  switch response.result{    case .success (let data):     guard let value = data as? JSON,        let eventsArrayJSON = value["ABDC"] as? [JSON]     else { fatalError() }     let struct_name = [Struct_Name].from(jsonArray: eventsArrayJSON)//the JSON deserialization is done here, after this line you can do anything with your JSON     for i in 0 ..

The output from the code above:

qwerty uiop 1234 asdf 


回答9:

 pod 'Alamofire'  pod 'SwiftyJSON'  pod 'ReachabilitySwift'    import UIKit import Alamofire import SwiftyJSON import SystemConfiguration  class WebServiceHelper: NSObject {      typealias SuccessHandler = (JSON) -> Void     typealias FailureHandler = (Error) -> Void      // MARK: - Internet Connectivity      class func isConnectedToNetwork() -> Bool {          var zeroAddress = sockaddr_in()         zeroAddress.sin_len = UInt8(MemoryLayout.size)         zeroAddress.sin_family = sa_family_t(AF_INET)          guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {             $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {                 SCNetworkReachabilityCreateWithAddress(nil, $0)             }         }) else {             return false         }          var flags: SCNetworkReachabilityFlags = []         if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {             return false         }          let isReachable = flags.contains(.reachable)         let needsConnection = flags.contains(.connectionRequired)          return (isReachable && !needsConnection)     }      // MARK: - Helper Methods      class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)     {         if isConnectedToNetwork() {              print(strURL)              if isShowLoader == true {                  AppDelegate.getDelegate().showLoader()             }              Alamofire.request(strURL).responseJSON { (resObj) -> Void in                  print(resObj)                  if resObj.result.isSuccess {                     let resJson = JSON(resObj.result.value!)                      if isShowLoader == true {                         AppDelegate.getDelegate().dismissLoader()                     }                      debugPrint(resJson)                     success(resJson)                 }                 if resObj.result.isFailure {                     let error : Error = resObj.result.error!                      if isShowLoader == true {                         AppDelegate.getDelegate().dismissLoader()                     }                     debugPrint(error)                     failure(error)                 }             }         }else {               CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)         }     }      class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler,  failure :@escaping FailureHandler){         if isConnectedToNetwork() {              if isShowLoader == true {                 AppDelegate.getDelegate().showLoader()             }               Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in                  print(resObj)                  if resObj.result.isSuccess {                     let resJson = JSON(resObj.result.value!)                      if isShowLoader == true {                         AppDelegate.getDelegate().dismissLoader()                     }                      success(resJson)                 }                 if resObj.result.isFailure {                     let error : Error = resObj.result.error!                      if isShowLoader == true {                         AppDelegate.getDelegate().dismissLoader()                     }                      failure(error)                 }              })         }     else {              CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)     }      }        class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure :@escaping FailureHandler)     {         if isConnectedToNetwork()         {              if isShowLoader == true             {                 AppDelegate.getDelegate().showLoader()             }              Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in                  print(resObj)                  if resObj.result.isSuccess                 {                     let resJson = JSON(resObj.result.value!)                      if isShowLoader == true                     {                         AppDelegate.getDelegate().dismissLoader()                     }                      success(resJson)                 }                  if resObj.result.isFailure                 {                     let error : Error = resObj.result.error!                      if isShowLoader == true                     {                         AppDelegate.getDelegate().dismissLoader()                     }                      failure(error)                 }             })         }else {             CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)         }     }       class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)     {         if isConnectedToNetwork() {             if isShowLoader == true             {                 AppDelegate.getDelegate().showLoader()             }              Alamofire.upload(                 multipartFormData: { multipartFormData in                     if let imageData = UIImageJPEGRepresentation(image, 0.5) {                         multipartFormData.append(imageData, withName: "Image.jpg")                     }                      for (key, value) in params! {                          let data = value as! String                          multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)                         print(multipartFormData)                     }                 },                 to: strURL,                 encodingCompletion: { encodingResult in                     switch encodingResult {                     case .success(let upload, _, _):                         upload.responseJSON { response in                             debugPrint(response)                             //let datastring = String(data: response, encoding: String.Encoding.utf8)                            // print(datastring)                         }                     case .failure(let encodingError):                         print(encodingError)                         if isShowLoader == true                         {                             AppDelegate.getDelegate().dismissLoader()                         }                          let error : NSError = encodingError as NSError                         failure(error)                     }                      switch encodingResult {                     case .success(let upload, _, _):                         upload.responseJSON { (response) -> Void in                              if response.result.isSuccess                             {                                 let resJson = JSON(response.result.value!)                                  if isShowLoader == true                                 {                                     AppDelegate.getDelegate().dismissLoader()                                 }                                  success(resJson)                             }                              if response.result.isFailure                             {                                 let error : Error = response.result.error! as Error                                  if isShowLoader == true                                 {                                     AppDelegate.getDelegate().dismissLoader()                                 }                                  failure(error)                             }                          }                     case .failure(let encodingError):                         if isShowLoader == true                         {                             AppDelegate.getDelegate().dismissLoader()                         }                          let error : NSError = encodingError as NSError                         failure(error)                     }                 }             )         }         else         {             CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)         }     }  }   ==================================   Call Method   let aParams : [String : String] = [                 "ReqCode" : Constants.kRequestCodeLogin,                 ]              WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in                   if "\(responceObj["RespCode"])" != "1"                 {                     let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)                     let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in                     }                     alert.addAction(OKAction)                     self.present(alert, animated: true, completion: nil)                 }                 else                 {                     let aParams : [String : String] = [                         "Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,                         ]                     CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)                  }                 }, failure:                 { (error) in                      CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)             })         } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!