Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The json(/gson) deserializer for mix-structure response
import android.os.Parcelable
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
sealed class ResponseWrapper<out T> {
class Anomaly(val value: com.xxx.model.wrapper.Anomaly) : 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, Anomaly::class.java))
}
// 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
You can’t perform that action at this time.