How to parse JSON response from Alamofire API in Swift?
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)") } }
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) } }
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) invar 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"}
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' } ]}