Decoding Json with Alamofire

In this article, I decode a Json, which received with Alamofire, to a struct conforming to Decodable protocol. Firstly, I enabled Alamofire with Cocoapods.

pod 'Alamofire', '~> 5.4'

Assume that receiving the Json below with Alamofire.

{
  "records": [
    { "name": "Starbucks", "image": "your-image-url-here" },
    { "name": "Caribou", "image": "your-image-url-here" },
    { "name": "Starbucks", "image": "your-image-url-here" },
    { "name": "Starbucks", "image": "your-image-url-here" },
    { "name": "Caribou", "image": "your-image-url-here" }
  ]
}

Define a struct as below. The struct conforms to Decodable protocol. Note that the name of property and the key of Json have the same name.

struct Records: Decodable {
    let records: [Record]
}
struct Record: Decodable {
    let name: String
    let image: String
}

After requesting the response with Alamofire, decode the Json inside the responseJSON which defined in Alamofire. Pass the type of the struct of response type and response.data to the decode function from JSONDecoder. Actually, I defined data inside guard and it refers response.data, I passed data instead of response.data.

AF.request("your-json-url-here", method: .get)
    .responseJSON { response in
        guard let data = response.data else {
            return
        }

        do {
            let records = try JSONDecoder.init().decode(Records.self, from: data)
            // do something here
        } catch {
            // TODO
        }
    }

Now I successfully decoded Json to struct which conforms to Decodable protocol.

About me

Experienced software developer. Technical lead at Fuller, Inc. My speciality is developing Android native app. I'm living in Tsukuba Japan, with my family, dogs, and cats :)

Here is more detailed profile.