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)
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.
Fair enough, I am using ["a", "b"]. In case someone else wants the adapter:
https://github.com/loewenfels/dep-graph-releaser/blob/66c822830aa38ac6b4a2278dfe0020d551782bf0/dep-graph-releaser-serialization/src/main/kotlin/ch/loewenfels/depgraph/serialization/PairAdapterFactory.kt
Most helpful comment
Fair enough, I am using
["a", "b"]. In case someone else wants the adapter:https://github.com/loewenfels/dep-graph-releaser/blob/66c822830aa38ac6b4a2278dfe0020d551782bf0/dep-graph-releaser-serialization/src/main/kotlin/ch/loewenfels/depgraph/serialization/PairAdapterFactory.kt