Moshi: Kotlin multiple @Transient fields

Created on 26 Dec 2018  路  2Comments  路  Source: square/moshi

Having more than one @ Transient field is causing following exception.

Exception in thread "main" java.lang.IllegalArgumentException: duplicate option: [text=\\u0000"]
    at okio.Options.of(Options.java:66)
    at com.squareup.moshi.JsonReader$Options.of(JsonReader.java:538)
    at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:260)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:137)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:97)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:71)

Code to reproduce

data class TransientTest(
        val a: String,
        @Transient
        val b: String? = "b",
        @Transient
        val c: String? = "c"
)

fun main(args: Array<String>) {

    val adapter = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
            .adapter(TransientTest::class.java)

    val test = TransientTest("a")

    adapter.toJson(test)
}
bug

Most helpful comment

Can someone please put that finally into the next release? It's been a year.

All 2 comments

Probably not ideal, but anyway this fixes the issue:

KotlinJsonAdapter.kt:260

var i=0
val options = JsonReader.Options.of(*bindings.map { it?.name ?: "moshi_jsonreader_ignored_${i++}" }.toTypedArray())

Instead of:

val options = JsonReader.Options.of(*bindings.map { it?.name ?: "\u0000" }.toTypedArray())

Can someone please put that finally into the next release? It's been a year.

Was this page helpful?
0 / 5 - 0 ratings