Skip to content

Instantly share code, notes, and snippets.

@mg6maciej
Created May 6, 2017 10:07
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mg6maciej/48f7829e386254bb945b7fc39ce21a19 to your computer and use it in GitHub Desktop.
Save mg6maciej/48f7829e386254bb945b7fc39ce21a19 to your computer and use it in GitHub Desktop.
Moshi generic type adapters
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import java.lang.reflect.Type
// val adapter = moshi.listAdapter<MyModel>()
// val adapter = moshi.mapAdapter<String, List<MyModel>>(valueType = listType<MyModel>())
inline fun <reified E> Moshi.listAdapter(elementType: Type = E::class.java): JsonAdapter<List<E>> {
return adapter(listType<E>(elementType))
}
inline fun <reified K, reified V> Moshi.mapAdapter(
keyType: Type = K::class.java,
valueType: Type = V::class.java): JsonAdapter<Map<K, V>> {
return adapter(mapType<K, V>(keyType, valueType))
}
inline fun <reified E> listType(elementType: Type = E::class.java): Type {
return Types.newParameterizedType(List::class.java, elementType)
}
inline fun <reified K, reified V> mapType(
keyType: Type = K::class.java,
valueType: Type = V::class.java): Type {
return Types.newParameterizedType(Map::class.java, keyType, valueType)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment