Search code examples
androidjsonkotlinmoshi

Moshi adapter for annotated model


I'm currently using a Moshi adapter to convert some json raw to a given type. It works fine until I used an annotated model.

I'm guessing I should add another params to my adapter beside Player::class.java but I don't know what.

Here is an exemple:

data class Player(
    val username: String,
    @Json(name = "lucky number")
    val luckyNumber: Int
)

private val playerStubRaw = "{\n" +
    "  \"username\": \"jesse\",\n" +
    "  \"lucky number\": 32\n" +
    "}"

@Test
fun doSomething() {
    val moshi = Moshi.Builder().build()
    val player = moshi.adapter(Player::class.java).fromJson(playerStubRaw)
    // player.luckyNumber == 0
}

luckyNumber value is 0 and not 32.

Any idea what I should do to make it work?

Thanks in advance,


Solution

  • To work with Kotlin, Moshi requires either the reflective KotlinJsonAdapterFactory (from the moshi-kotlin artifact) or code-gen adapters (from the moshi-kotlin-codegen artifact). https://github.com/square/moshi#kotlin
    In a future release of Moshi, a proper error will be thrown to state this requirement.