IskandarH
IskandarH

Reputation: 99

How to decode JSON data from Alamofire request

I'm trying to decode the json data after fetching json with alamofire. I have created the model class but i don't understand how to decode the data.

Alamofire.request("http://somerandomlink.xyz").responseJSON { (response) in
            switch response.result {
            case .failure(let error):
                print(error)
            case .success(let data):
                do {
                    //print(response)
                    print("data: \(data)")
                } catch let error {
                    print(error)
                }
            }
        }

Model

struct LoremIpsum: Codable {
   let var1: String
   let var2: String
   let var3: String
}

Upvotes: 1

Views: 2808

Answers (3)

vikas patidar
vikas patidar

Reputation: 23

        guard let users = try? JSONDecoder().decode(LoremIpsum.self, from: response) else {
            return
        }
        

Upvotes: 0

Anjali Aggarwal
Anjali Aggarwal

Reputation: 629

You can also use .responseData instead of responseJSON and then in the success case you can try decoding using JSONDecoder as follows:

let decoder = JSONDecoder()
do {
     let users = try decoder.decode(LoremIpsum.self, from:data)
     print("Users list :", users)
    } catch {
     print(error)
 }

Upvotes: 0

Frankenstein
Frankenstein

Reputation: 16341

Alamofire has been updated to use Codable objects natively.

Use:

.responseDecodable(of: LoremIpsum.self) {

Instead of:

.responseJSON {

Upvotes: 1

Related Questions