Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
The json(/gson) deserializer for mix-structure response
import android.os.Parcelable
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
sealed class ResponseWrapper<out T> {
class Anomaly(val value: : ResponseWrapper<Nothing>()
class Single<T : Parcelable>(val value: T) : ResponseWrapper<T>()
class List<T : ArrayList<out Parcelable>>(val value: T) : ResponseWrapper<T>()
object ParseError : ResponseWrapper<Nothing>()
class ResponseJsonDeserializer : JsonDeserializer<ResponseWrapper<*>> {
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): ResponseWrapper<*> {
val obj = json.asJsonObject
val rltType = (typeOfT as ParameterizedType).actualTypeArguments[0]
if (obj.isJsonObject) {
val anomaly = obj.get("anomaly")
if (anomaly != null) {
// Return anomaly
return ResponseWrapper.Anomaly(context.deserialize(obj,
// Return single object
return ResponseWrapper.Single(context.deserialize(obj, rltType))
} else if (obj.isJsonArray) {
// Return a list
return ResponseWrapper.List(context.deserialize(obj, rltType))
// Parse failed
return ResponseWrapper.ParseError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment