Skip to content

Instantly share code, notes, and snippets.

@monday8am
Last active April 23, 2018 09:48
Show Gist options
  • Save monday8am/befe53b902ededc1555df24669e6023a to your computer and use it in GitHub Desktop.
Save monday8am/befe53b902ededc1555df24669e6023a to your computer and use it in GitHub Desktop.
Result serializer
override fun serialize(src: Result<*, *>?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement? {
return when (src) {
// Ignore Loading or Err states
is Result.Loading -> context?.serialize("")
is Result.Err -> context?.serialize("")
// Thanks God that the original type is passed inside the
// ParameterizedType field.
// It lets us to use it for a real serialization
is Result.Ok -> {
val parameterizedType = typeOfSrc as ParameterizedType
// Basically we're serializing the Result<T, E> as a simple
// T, only when the Result is .Ok
return context?.serialize(src.value, parameterizedType.actualTypeArguments[0])
}
null -> null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment