LoginSignup
0
0

More than 5 years have passed since last update.

Retrofit+moshi+kotshiが動かない話

Last updated at Posted at 2018-08-22

以下のコードを動かそうとすると。Unresolved reference: KotshiApplicationJsonAdapterFactoryというエラーが出て動きません。

kotshiのReadmeにはKotshiApplicationJsonAdapterFactoryはあなたのカスタムアダプタだと書いてありましたが、他のプロジェクトを見るとapp/build/generated配下に生成されている物を発見しました。
これはkaptで生成させるものなのでしょうか?私のプロジェクトはそうなりません。どうしたら生成されますか?それとも自分で書くものなのでしょうか?その場合はどのように書いたらよいでしょうか?

このコードはどうしたら動くようになりますか?

apply plugin: 'kotlin-kapt'
dependencies {
    // 略
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.moshi:moshi:1.6.0'
    implementation 'com.squareup.retrofit2:converter-moshi:2.3.0'
    implementation 'se.ansman.kotshi:api:1.0.4'
    kapt 'se.ansman.kotshi:compiler:1.0.4'
}

    override fun onResume() {
        super.onResume()
        simpleService()
    }

    @JsonSerializable
    class Contributor(
            val login: String,
            val contributions: Int,
            @Json(name = "node_id") val nodeId: String
    )

    interface GitHub {
        @GET("/repos/{owner}/{repo}/contributors")
        fun contributors(
                @Path("owner") owner: String,
                @Path("repo") repo: String): Call<List<Contributor>>
    }

    private fun simpleService() {
        val moshi = Moshi.Builder().add(ApplicationJsonAdapterFactory.INSTANCE).build()
        val retrofit = Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(MoshiConverterFactory.create(moshi))
                .build()

        val github = retrofit.create(GitHub::class.java)
        val call = github.contributors("square", "retrofit")

        call.enqueue(object : Callback<List<Contributor>> {
            override fun onResponse(call: Call<List<Contributor>>, response: retrofit2.Response<List<Contributor>>) {
                // Response https://api.github.com/repos/square/retrofit/contributors
                val contributors = response.body()
                for (contributor in contributors!!) {
                    Log.d("simpleService", contributor.login + " (" + contributor.contributions + ") : " + contributor.nodeId)
                }
            }

            override fun onFailure(call: Call<List<Contributor>>, t: Throwable) {
                Log.d("simpleService", t.toString())
            }
        })
    }

    @KotshiJsonAdapterFactory
    abstract class ApplicationJsonAdapterFactory : JsonAdapter.Factory {
        companion object {
            val INSTANCE: ApplicationJsonAdapterFactory = KotshiApplicationJsonAdapterFactory()
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0