Created
June 3, 2019 16:29
-
-
Save nekocode/1f97a1743e540e76982d40ed8fff4078 to your computer and use it in GitHub Desktop.
The json(/gson) deserializer for mix-structure response
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
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