Moshi: Serialize Map<String,Long> fails in Kotlin

Created on 11 Nov 2017  路  1Comment  路  Source: square/moshi

Hi,

i麓m trying to serialize a Map in Kotlin. This fails with an java.lang.IllegalArgumentException.

Moshi.Builder().build()
            .adapter<Map<String, Long>>(Types.newParameterizedType(Map::class.java, String::class.java, Long::class.java))
            .toJson(mapOf("a" to 1L))
Exception in thread "main" java.lang.IllegalArgumentException
    at com.squareup.moshi.Types.checkNotPrimitive(Types.java:496)
    at com.squareup.moshi.Types$ParameterizedTypeImpl.<init>(Types.java:518)
    at com.squareup.moshi.Types.newParameterizedType(Types.java:75)
    at de.kajzar.settings.MapTestKotlinKt.main(MapTestKotlin.kt:17)

It works fine in java. It also works fine in Kotlin if I wrap it e.g. data class Wrapper(val map: Map<String, Long>). Is this intentional?

Thanks,
Fabian

Most helpful comment

Yep, Kotlin references the primitive long type there.
You'll want to use Long::class.javaObjectType instead to get the Long boxed type.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/java-object-type.html

In case of primitive types it returns corresponding wrapper classes.

>All comments

Yep, Kotlin references the primitive long type there.
You'll want to use Long::class.javaObjectType instead to get the Long boxed type.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/java-object-type.html

In case of primitive types it returns corresponding wrapper classes.

Was this page helpful?
0 / 5 - 0 ratings