Created
August 2, 2017 10:45
-
-
Save babedev/c3a20cac021cde6add8ebea821ca0243 to your computer and use it in GitHub Desktop.
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
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