---
# System prepended metadata

title: 'Retrofit2 串接API [台南市資料開放平台]'
tags: [retrofit, Android, kotlin]

---

# Retrofit2 串接API [台南市資料開放平台]

## 下面程式碼示範用retrofit取得台南市及時停車場相關資訊

#### 事前準備工作
```kotlin=
//於專案build.gradle:app 新增下面三行
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
```
```kotlin= 
//於專案資料夾manifests內的AndroidManifest.xml新增下面這行啟用網路功能
<uses-permission android:name="android.permission.INTERNET" />
```
##### 安裝套件
安裝 JSON To Kotlin Class
他可以迅速幫助你轉換JSON格式成data class
![](https://i.imgur.com/vTnkDie.png)
#### [這是台南市開放資料平台的連結](https://opengov.tainan.gov.tw/OpenApi/api/doc/v3)

##### 我們使用 "臺南市停車場即時剩餘車位資訊"
這是及時車位Get到的資料一部分
![](https://i.imgur.com/IGKvoI5.png)

#### 建立資料類別   [*ApiDataClass.kt*]
新增一個.kt檔 ,開啟檔案, 按ALT+ K, 開啟JSON To Kotlin Class, 將剛剛Get到的JSON貼上去, class name,自行命名
![](https://i.imgur.com/UJydCIe.png)

#### 自動產出資料類別
```kotlin=
data class GetData(
    val contentType: String,
    val `data`: List<ApiData>,
    val id: String,
    val isImage: Boolean,
    val success: Boolean
)

data class ApiData(
        val address: String?,
        val car: Int,
        val carDis: Int,
        val carDis_total: Int,
        val carGreen: Int,
        val carGreen_total: Int,
        val carWoman: Int,
        val carWoman_total: Int,
        val car_total: Int,
        val chargeFee: String?,
        val chargeTime: String?,
        val code: String?,
        val id: String?,
        val largeCar: Int,
        val largeCar_total: Int,
        val lnglat: String?,
        val moto: Int,
        val motoDis: Int,
        val motoDis_total: Int,
        val moto_total: Int,
        val name: String?,
        val typeId: String?,
        val typeName: String?,
        val update_time: String?,
        val zone: String?,
        val zoneId: String?
)
```
#### 建立Interface [*ApiInterFace.kt*]


```kotlin    
interface ApiInterface {

    @GET("api/service/Get/c3604e1d-c4e1-4224-9d41-084ce299c3bf")
    fun login (): Call<GetData>
}
```
#### 上面的Call>GetData> 對應到data class

#### *MainActivity.kt*

```kotlin=
class MainActivity : AppCompatActivity() {
    private val baseUrl = "https://opengov.tainan.gov.tw:443/OpenApi/"
    private val retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    private val api = retrofit.create(ApiInterface::class.java)
    lateinit var send:Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.btn_info).setOnClickListener() {
            api.login().enqueue(object : Callback<GetData> {
                override fun onFailure(call: Call<GetData>, t: Throwable) {
                    Log.d("Error","連線失敗")
                }

                override fun onResponse(call: Call<GetData>, response: Response<GetData>) {
                    val lis =  response.body()!!.data
                    runOnUiThread {
                        for(i in lis.indices) {
                            var address = lis[i].address
                            var name = lis[i].name
                            //Log.d("size", "size = ${lis.size}")
                            findViewById<TextView>(R.id.tv_show).text =  "address = $address , name = $name!"
                        }
                    }
                }
            })
        }
    }
}
```

##### 觀察Get的JSON資料
**我們所需要的資訊都在 data:裡面**
![](https://i.imgur.com/1z1E9ZG.png)
##### 所以透過程式碼第20行取得回傳資料的data 這個List就可以處理想要的資料了

###### tags: `kotlin` `Android` `retrofit`