okuzawatsの日記

Android / Kotlin Enthusiast 🤖

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.

#iOS #Swift

About me 😎

profile

茨城県つくば市在住のソフトウェアエンジニアです。専門領域はAndroidアプリ開発で、特にアーキテクチャに興味があります。某社でAndroidアプリ開発のテックリードをしています。

Jetpack ComposeによるAndroid MVVMアーキテクチャ入門の著者です。

👉 もっと詳しく

Writing 📝

Android MVVMアーキテクチャ入門

Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。

👉 もっと詳しく