Original Fidesmo Result JsonSerializer
This file contains 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
package com.fidesmo.devicemanager.helpers | |
import com.google.gson.* | |
import com.google.gson.internal.LinkedTreeMap | |
import java.lang.reflect.ParameterizedType | |
import java.lang.reflect.Type | |
import java.lang.reflect.WildcardType | |
class ResultSerializer : JsonSerializer<Result<*, *>>, JsonDeserializer<Result<*, *>> { | |
private val gson: Gson = Gson() | |
override fun serialize(src: Result<*, *>?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement? { | |
return when (src) { | |
is Result.Loading -> context?.serialize("") | |
is Result.Err -> context?.serialize("") | |
is Result.Ok -> { | |
val parameterizedType = typeOfSrc as ParameterizedType | |
return context?.serialize(src.value, parameterizedType.actualTypeArguments[0]) | |
} | |
null -> null | |
} | |
} | |
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Result<*, *>? { | |
return when { | |
json?.isJsonObject == true -> { | |
val parameterizedType = typeOfT as ParameterizedType | |
return Result.ok(context?.deserialize<Any>(json, parameterizedType.actualTypeArguments[0])!!) | |
} | |
json?.isJsonArray == true -> { | |
val parameterizedType = typeOfT as ParameterizedType | |
if (parameterizedType.actualTypeArguments[0] is WildcardType) { | |
val internalListType = (parameterizedType.actualTypeArguments[0] as WildcardType).upperBounds[0] as ParameterizedType | |
val arr = context?.deserialize<Any>(json, parameterizedType.actualTypeArguments[0]) as ArrayList<*> | |
val result = arr.map { linkedTreeMap -> | |
val jsonElement = gson.toJsonTree(linkedTreeMap as LinkedTreeMap<*, *>).asJsonObject | |
return@map context.deserialize<Any>(jsonElement, internalListType.actualTypeArguments[0]) | |
} | |
return Result.ok(result) | |
} else { | |
return Result.ok(context?.deserialize<Any>(json, parameterizedType.actualTypeArguments[0])!!) | |
} | |
} | |
else -> Result.Loading | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment