Skip to content

Instantly share code, notes, and snippets.

@mypplication
Created February 28, 2022 14:00
Show Gist options
  • Save mypplication/7996709a6e02619cd002673d9d6bce07 to your computer and use it in GitHub Desktop.
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
/**
* 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