我正在尽可能接近https://proandroiddev.com/getting-started-using-moshi-for-json-parsing-with-kotlin-5a460bf3935a中的示例,但仍然无法运行。
在我的 Gradle 中,我有
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
和
dependencies {
implementation "com.squareup.moshi:moshi:1.8.0"
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.8.0'
}
我有课
@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
)
当我如下运行测试时
@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)
}
失败了
Failed to find the generated JsonAdapter class for 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
)
当我将其移动到主文件夹时,它就可以工作(因为现在可以生成适配器)
在另一种情况下,您应该读取整个堆栈跟踪,但有异常,如下所示:
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> []
然后寻找解决方案。我发现这个适合我的情况:Moshi序列化泛型类“无法找到生成的 JsonAdapter 构造函数...”.
我来晚了一点,但除了允许在测试包中生成代码之外,请务必拥有
kaptTest
和 kaptAndroidTest
。
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")