0

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,

loutry
  • 3
  • 3
  • To use Moshi with Kotlin, install the reflective KotlinJsonAdapterFactory on the builder or use moshi-codegen. – Eric Cochran Feb 05 '19 at 06:39
  • Thanks @EricCochran! I simply use: Moshi.Builder().add(KotlinJsonAdapterFactory()).build() as you suggested and it worked :) You could maybe add it as an answer so it could be accepted? – loutry Feb 06 '19 at 09:34

2 Answers2

0

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.

Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
0

With the moshi-kotlin-codegen artifact you also need to add @JsonClass(generateAdapter = true) on the class for the decoding to work correctly and not set the property to a default of 0

So after adding the kotlin-kapt plugin and the dependency kapt "com.squareup.moshi:moshi-kotlin-codegen:1.8.0" to the app build gradle annotate the class as below:

@JsonClass(generateAdapter = true)
data class Player(
    val username: String,
    @Json(name = "lucky number")
    val luckyNumber: Int
)
alexy
  • 464
  • 5
  • 6