Reputation: 60241
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?
Upvotes: 4
Views: 10291
Reputation: 905
I'm a little late to the party here, but be sure to have kaptTest
and kaptAndroidTest
in addition to allow code generation in the test packages.
implementation("com.squareup.moshi:moshi-kotlin:1.15.1")
kapt("com.squareup.moshi:moshi-kotlin-codegen:1.15.1")
kaptTest("com.squareup.moshi:moshi-kotlin-codegen:1.15.1")
kaptAndroidTest("com.squareup.moshi:moshi-kotlin-codegen:1.15.1")
Upvotes: 0
Reputation: 28835
In another case you should read a whole stacktrace with exception, like this:
TestRunner: java.lang.RuntimeException: Failed to find the generated JsonAdapter
constructor for 'class SomeGenericClass'. Suspiciously, the type was not parameterized
but the target class 'SomeGenericClassJsonAdapter' is generic.
Consider using Types#newParameterizedType() to define these missing type variables.
...
Caused by: java.lang.NoSuchMethodException: SomeGenericClassJsonAdapter.<init> []
Then search for a solution. I found this one for my situation: Moshi serialize generic classes "Failed to find the generated JsonAdapter constructor...".
Upvotes: 0
Reputation: 60241
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)
Upvotes: 2