Skip to content

Instantly share code, notes, and snippets.

@monday8am
Created April 20, 2018 17:18
Show Gist options
  • Save monday8am/bce54f4852ae9ba70a3c28413b6e46d0 to your computer and use it in GitHub Desktop.
Save monday8am/bce54f4852ae9ba70a3c28413b6e46d0 to your computer and use it in GitHub Desktop.
Original Fidesmo Result JsonSerializer
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