Skip to content

Instantly share code, notes, and snippets.

@babedev
Created August 2, 2017 10:45
Show Gist options
  • Save babedev/c3a20cac021cde6add8ebea821ca0243 to your computer and use it in GitHub Desktop.
Save babedev/c3a20cac021cde6add8ebea821ca0243 to your computer and use it in GitHub Desktop.
GsonBuilder().registerTypeAdapterFactory(NullStringToEmptyAdapterFactory())
.create()
.run {
return fromJson(this@toObject, T::class.java)
}
class NullStringToEmptyAdapterFactory : TypeAdapterFactory {
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
if (type.rawType != String::class.java) {
return null
}
return StringAdapter() as TypeAdapter<T>
}
}
class StringAdapter : TypeAdapter<String>() {
override fun read(reader: JsonReader): String {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
return ""
}
return reader.nextString()
}
override fun write(writer: JsonWriter, value: String?) {
if (value == null) {
writer.nullValue()
} else {
writer.value(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment