Moshi: Right way for a generic adapter?

Created on 17 Jan 2017  路  4Comments  路  Source: square/moshi

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?

documentation

Most helpful comment

No documentation yet?

All 4 comments

Yep, you did it perfectly. I'll get some more docs.

Yep.

No documentation yet?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vganin picture vganin  路  3Comments

VictorAlbertos picture VictorAlbertos  路  5Comments

rephiscorth picture rephiscorth  路  5Comments

bfarrelladelphi picture bfarrelladelphi  路  4Comments

rephiscorth picture rephiscorth  路  5Comments