Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize generic class members with moshi?

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.

like image 922
SpecialSnowflake Avatar asked Sep 30 '18 13:09

SpecialSnowflake


Video Answer


1 Answers

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)
}
like image 82
Sachin Kasaraddi Avatar answered Sep 29 '22 07:09

Sachin Kasaraddi