Moshi: Platform kotlin.Pair<java.lang.String, java.lang.String> annotated [] requires explicit JsonAdapter to be registered

Created on 18 Apr 2018  路  4Comments  路  Source: square/moshi

Maybe I am doing something wrong but I think that should work out of the box. I get an IllegalArgumentException for the following:

val listPairStringType = Types.newParameterizedType(
    List::class.java,
    Types.newParameterizedType(Pair::class.java, String::class.java, String::class.java)
)
val listPairStringAdapter = moshi.adapter<List<Pair<String, String>>>(listPairStringType)

following the stack-trace:

Exception in thread "main" java.lang.IllegalArgumentException: Platform kotlin.Pair<java.lang.String, java.lang.String> annotated [] requires explicit JsonAdapter to be registered
        at com.squareup.moshi.ClassJsonAdapter$1.create(ClassJsonAdapter.java:51)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:100)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:58)
        at com.squareup.moshi.CollectionJsonAdapter.newArrayListAdapter(CollectionJsonAdapter.java:52)
        at com.squareup.moshi.CollectionJsonAdapter$1.create(CollectionJsonAdapter.java:36)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:100)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:58)

Most helpful comment

All 4 comments

From the README

Moshi refuses to serialize platform types (java.*, javax.*, and android.*) without a user-provided type adapter. This is intended to prevent you from accidentally locking yourself to a specific JDK or Android release.

Use an adapter that uses only the public API for types you don't control (instead of using the built-in reflective adapter that relies on implemention details of a version of the type).

Thanks for the quick reply. Maybe worth considering to add an adapter for Pair since it is so commonly used in Kotlin.

Should pairs be encoded like a pair:

["a", "b"]

Or like a data class:

{
  "first": "a",
  "second": "b"
}

I don't feel comfortable having Moshi make this choice for you.

Was this page helpful?
0 / 5 - 0 ratings