I am fetching a JSON object which contains a generic member (data can be of a few different types). The class currently looks like this:
@Parcelize
data class Children<T: Parcelable>(
@Json(name = "type") val type: String,
@Json(name = "data") val data: T
): Parcelable
How do I go about being able to deserialize/map the correct object type with moshi?
@Parcelize
data class Comment<T : Parcelable>(
@Json(name = "replies") val replies: Children<T>,
@Json(name = "count") val count: Int,
@Json(name = "children") val childs: List<String>
) : Parcelable
Or how about instances such as this? I should note Comment
can take a generic param of Comment
thus resulting in a loop.
Add below inlines in an MoshiExtensions and try to use them accordingly.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With