もくじ
ライブラリを入手する
- Fuel – APIアクセス
- Moshi – JSONデータのパース
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.bs_tender"> + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> <activity android:name=".MatchListActivity" android:label="マッチリスト" android:theme="@style/AppTheme"> </activity> <activity android:name=".MatchActivity" /> <activity android:name=".SplashActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity" /> <activity android:name=".SubActivity" /> <activity android:name=".PicassoActivity" /> </application> </manifest>
build.gradle (Module: app)
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.example.bs_tender" minSdkVersion 15 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.core:core-ktx:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.+" implementation 'com.squareup.picasso:picasso:2.71828' + implementation 'com.github.kittinunf.fuel:fuel:1.11.0' + implementation 'com.github.kittinunf.fuel:fuel-gson:1.11.0' + implementation "com.squareup.moshi:moshi:1.5.0" + implementation "com.squareup.moshi:moshi-kotlin:1.5.0" }
シンプルに検証しよう
jsonを用意した
{"name": "satou","age": "20"}
Activity.ktを用意する
package com.example.bs_tender import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.github.kittinunf.fuel.gson.responseObject import com.github.kittinunf.fuel.httpGet class MatchListActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_match_list2) "https://www.yuulinux.tokyo/demo/bs-tender-server-mock/test.json".httpGet().responseObject<User> { req, res, result -> val(user,err) = result println("user:${user}") } } } data class User ( var name: String, var age: String )
これで外部APIにGETでJSONを取得して変数に格納できることがわかりました。
配列のJSONを扱う
リストのJSONを扱うAPIなら。
users.json
[{"user_id": 1,"nickname": "社長","gender_code": 1,"birth_date": "1981/01/13","image_url": "https://www.yuulinux.tokyo/demo/bs-tender-server-mock/cat1.jpg"}, {"user_id": 2,"nickname": "女子","gender_code": 2,"birth_date": "1981/02/13","image_url": "https://www.yuulinux.tokyo/demo/bs-tender-server-mock/cat2.jpg"}]
Activity.kt
package com.example.bs_tender import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.github.kittinunf.fuel.core.ResponseDeserializable import com.squareup.moshi.Moshi import com.github.kittinunf.fuel.httpGet import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Types class MatchListActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_match_list2) val baseUrl: String = "https://www.yuulinux.tokyo/demo/bs-tender-server-mock" val endpoint: String = "/match.json" val url: String = baseUrl + endpoint url.httpGet().responseObject(UserListDeserializer()) { req, res, result -> val(users,err) = result println("people:${users}") } } } class UserListDeserializer : ResponseDeserializable<List<User>> { override fun deserialize(content: String): List<User>? { val moshi = Moshi.Builder().build() val type = Types.newParameterizedType(List::class.java, User::class.java) val listAdapter: JsonAdapter<List<User>> = moshi.adapter(type) return listAdapter.fromJson(content) } } data class User ( var user_id: Int, var nickname: String, var gender_dode: Int, var birth_date: String, var image_url: String )
@see
- AndroidからAPIを叩いてJSON取って中身を表示させるまで
- Kotlin Android JSON Parsing using URL
- [Kotlin]内部クラスを理解する
- Fuelを使ってWebAPIを叩こう
- Kotlin HTTP Example (Using Fuel Http)
JSONパース