I just created an adapter for a generic type. I could not really find documentation about this and I think this is something that should be documented with examples as it acutally was quite hard to figure out.
I first started writing an adapter for SparseArrayCompat:
class SparseArrayCompatAdapter<T>(private val adapter: JsonAdapter<T>) : JsonAdapter<SparseArrayCompat<T>>() {
override fun toJson(writer: JsonWriter, sparseArray: SparseArrayCompat<T>) {
....
}
override fun fromJson(reader: JsonReader): SparseArrayCompat<T> {
...
}
}
However when registering this adapter, I got an exception that I need to register a specific type adapter for SparseArrayCompat<Double>.
Then I tried a lot and came up with a factory that delegates to the adapter:
object SparseArrayFactory : JsonAdapter.Factory {
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<*>? {
val rawType = Types.getRawType(type)
if (rawType == SparseArrayCompat::class.java && type is ParameterizedType) {
val subType = type.actualTypeArguments.first()
val adapter: JsonAdapter<Any> = moshi.adapter(subType)
return SparseArrayCompatAdapter(adapter)
}
return null
}
}
Is this the way moshi intended to do this?
Yep, you did it perfectly. I'll get some more docs.
fold this into https://github.com/square/moshi/issues/136?
Yep.
No documentation yet?
Most helpful comment
No documentation yet?