Created
May 6, 2017 10:07
-
-
Save mg6maciej/48f7829e386254bb945b7fc39ce21a19 to your computer and use it in GitHub Desktop.
Moshi generic type adapters
This file contains hidden or 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