
com.pubnub.internal.utils.PolymorphicDeserializer.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pubnub-core-impl Show documentation
Show all versions of pubnub-core-impl Show documentation
PubNub is a cross-platform client-to-client (1:1 and 1:many) push service in the cloud, capable of broadcasting real-time messages to millions of web and mobile clients simultaneously, in less than a quarter second!
package com.pubnub.internal.utils
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import java.lang.reflect.Type
internal class PolymorphicDeserializer(
private val defaultClass: Class? = null,
private val findTargetClass: (JsonElement, Type) -> Class?,
) : JsonDeserializer {
companion object {
inline fun dispatchByFieldsValues(
fields: List,
mappingFieldValuesToClass: Map, Class>,
defaultClass: Class? = null,
): JsonDeserializer {
val mappingWithList: Map, Class> = mappingFieldValuesToClass.mapKeys { it.key.toList() }
return PolymorphicDeserializer(defaultClass = defaultClass) { jsonElement, _ ->
val jsonObject = jsonElement.asJsonObject
val fieldsValues: List = fields.map { jsonObject[it].asString }.toList()
mappingWithList[fieldsValues]
}
}
}
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext,
): T {
val targetClass =
findTargetClass(json, typeOfT) ?: defaultClass
?: error("When deserializing to $typeOfT no target class have been found and default class was not provided")
return context.deserialize(json, targetClass)
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy