Created
February 28, 2022 14:00
-
-
Save mypplication/7996709a6e02619cd002673d9d6bce07 to your computer and use it in GitHub Desktop.
Gson TypeAdapterFactory to handle when API return empty array instead of null value
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
/** | |
* Usage : gsonBuilder.registerTypeAdapterFactory(JsonPreProcessingAdapterFactory()) | |
**/ | |
class JsonPreProcessingAdapterFactory : TypeAdapterFactory { | |
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { | |
if (!Object::class.java.isAssignableFrom(type.rawType) || | |
Iterable::class.java.isAssignableFrom(type.rawType) | |
) | |
return null | |
val delegate = gson.getDelegateAdapter(this, type) | |
return object : TypeAdapter<T>() { | |
@Throws(IOException::class) | |
override fun write(out: JsonWriter, value: T?) { | |
delegate.write(out, value) | |
} | |
@Throws(IOException::class) | |
override fun read(`in`: JsonReader): T? { | |
return if (`in`.peek() == JsonToken.BEGIN_ARRAY) { | |
`in`.skipValue() | |
null | |
} | |
else | |
delegate.read(`in`) ?: null | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment