How to parse JSON response from Alamofire API in Swift?

210,221

Solution 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)
            }

        }

Solution 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"
}

Solution 3

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' }
  ]
}

Solution 4

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)!)")
            }
        }
    }

Solution 5

Swift 5

class User: Decodable {

    var name: String
    var email: String
    var token: String

    enum CodingKeys: String, CodingKey {
        case name
        case email
        case token
    }

    public required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.email = try container.decode(String.self, forKey: .email)
        self.token = try container.decode(String.self, forKey: .token)
    }
}

Alamofire API

    Alamofire.request("url.endpoint/path", method: .get, parameters: params, encoding: URLEncoding.queryString, headers: nil)
     .validate()
     .responseJSON { response in

        switch (response.result) {

            case .success( _):

            do {
                let users = try JSONDecoder().decode([User].self, from: response.data!)
                print(users)

            } catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
            }

             case .failure(let error):
                print("Request error: \(error.localizedDescription)")
         }
Share:
210,221
Developer
Author by

Developer

I am an iPhone Application Developer

Updated on June 13, 2021

Comments

  • Developer
    Developer almost 3 years

    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?)
    }
    
  • Sashi
    Sashi about 9 years
    I'm trying to use the SwiftyJson thing after installing but gives some 300 error's in SwiftyJson file, did anyone face the issue? i', using Xcode version 6.2, ios version 8.1, cocoaPods 36 as mentioned in the [github] (github.com/SwiftyJSON/SwiftyJSON) documentation .
  • Zia
    Zia over 8 years
    Dude. What are the errors? Ask a separate question and provide some details. SwiftyJSON is as beautiful as magic. Use it if possible.
  • Saqib Omer
    Saqib Omer over 8 years
    This is correct version for Swift 2.0 + Alamofire JSON parsing.
  • alex
    alex over 8 years
    hmm i am still getting fail built an error message: '(_, _, _) -> Void' is not convertible to 'Response<AnyObject, NSError> -> Void'
  • Joseph
    Joseph over 8 years
    @alex See this answer for what I used to resolve it.
  • Alex Worden
    Alex Worden over 8 years
    How do you get at the actual content of JSON? What type of object is this? The design and documentation is so obscure I can't figure it out and can't find any examples on the internet...
  • Joseph Geraghty
    Joseph Geraghty over 8 years
    I added a couple lines in my answer that should help.
  • thibaut noah
    thibaut noah about 8 years
    Thank you so much ! You have no idea how many things i tried to display properly the response message from the server, life savior !
  • dispatchswift
    dispatchswift over 7 years
    @JosephGeraghty having the encoding parameter results in the compiler telling me there is an extra argument call... Any idea?
  • Joseph Geraghty
    Joseph Geraghty over 7 years
    @jch-duran not positive, but I vaguely remember running into something similar a while back. I think it had something to do with the libraries not being updated or maybe not current with the swift version. Making sure you are on the latest versions might help
  • peter.swallow
    peter.swallow over 7 years
    An explanation of what all this code is would be helpful.
  • iljn
    iljn almost 7 years
    @AlexWorden agreed, this page helped me answer those questions and provides a nice solution: github.com/SwiftyJSON/SwiftyJSON
  • iljn
    iljn almost 7 years
    also posted an answer with an up to date implementation: stackoverflow.com/a/44448861/7263704
  • rmaddy
    rmaddy over 6 years
    The updated Swift 3 answer is a terrible example. Do not use NSDictionary in Swift 3. Use a Swift dictionary.
  • The Muffin Man
    The Muffin Man over 6 years
    Really should be converting the json string to a concrete swift object so that you can cleanly use it in a natural way. Accessing fields by their string name is ridiculous and prone to error.
  • Robin Macharg
    Robin Macharg about 6 years
    There's also an Alamofire Swifty-JSON-specific plugin that removes the need for the explicit JSON() conversion: github.com/SwiftyJSON/Alamofire-SwiftyJSON
  • Snymax
    Snymax over 5 years
    This should be the selected answer although you may want to update it as Alamofire has updated their methods a little bit
  • iGhost
    iGhost almost 5 years
    This help me, but I did have some problems with JSON method because throws Exception
  • Jon Shier
    Jon Shier almost 3 years
    If you have a Decodable type you should use responseDecodable, not responseJSON.
  • Eric Aya
    Eric Aya almost 3 years
    OP asks about Alamofire, not about URLRequest, so this is off-topic. Also your answer contains unrelated elements and seems to just be randomly copied from an existing code base. Please edit and make it specific to this question. Thanks.
  • Jiraheta
    Jiraheta over 2 years
    Thank you. I have used and reformatted to fit my needs on my project and I can vouch that this still holds for Swift 5.