-
-
Save Gamezpedia/3ef9f876adfef93324567bc6ccc86ea8 to your computer and use it in GitHub Desktop.
Moshi generic type adapters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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