Search code examples
kotlinmoshi

Moshi: Failed to find the generated JsonAdapter class for class


I'm following the example in https://proandroiddev.com/getting-started-using-moshi-for-json-parsing-with-kotlin-5a460bf3935a as close as possible, but still fail to run.

In my Gradle, I have

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

and

dependencies {
    implementation "com.squareup.moshi:moshi:1.8.0"
    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.8.0'
}

I have a class

@JsonClass(generateAdapter = true)
data class Movie (
    @Json(name = "vote_count") val voteCount: Int = -1,
    val id: Int,
    val title: String,
    @Json(name = "image_path") val imagePath: String,
    val overview: String
)

When I run my test as below

    @Test
    fun testMoshi() {
        val moviesJson: String = """
{
  "vote_count": 2026,
  "id": 19404,
  "title": "Example Movie",
  "image_path": "/example-movie-image.jpg",
  "overview": "Overview of example movie"
} 
        """.trimIndent()

        val moshi: Moshi = Moshi.Builder().build()
        val adapter: JsonAdapter<Movie> = moshi.adapter(Movie::class.java)
        val movie = adapter.fromJson(moviesJson)
    }

It fails Failed to find the generated JsonAdapter class for class...

What did I miss?


Solution

  • Apparently, it's because I put the below in Test Folder instead of Main Folder.

    @JsonClass(generateAdapter = true)
    data class Movie (
        @Json(name = "vote_count") val voteCount: Int = -1,
        val id: Int,
        val title: String,
        @Json(name = "image_path") val imagePath: String,
        val overview: String
    )
    

    When I have move it to the main folder, it works (as the adaptor now can be generated)