添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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'
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?

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)

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...".

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.