Skip to content

Instantly share code, notes, and snippets.

@Gamezpedia
Forked from mg6maciej/MoshiExtensions.kt
Created December 18, 2018 00:43
Show Gist options
  • Save Gamezpedia/3ef9f876adfef93324567bc6ccc86ea8 to your computer and use it in GitHub Desktop.
Save Gamezpedia/3ef9f876adfef93324567bc6ccc86ea8 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