Skip to content

Instantly share code, notes, and snippets.

@kenilt
Last active August 2, 2018 05:57
Show Gist options
  • Save kenilt/6f28d9f4cbbbebd14b36565f441a731b to your computer and use it in GitHub Desktop.
Save kenilt/6f28d9f4cbbbebd14b36565f441a731b to your computer and use it in GitHub Desktop.
Gson: Treat null as empty string or empty array
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException
class MutableListTypeAdapter<T>(private val delegate: TypeAdapter<MutableList<T>>?) : TypeAdapter<MutableList<T>>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: MutableList<T>?) {
delegate?.write(out, value)
}
@Throws(IOException::class)
override fun read(reader: JsonReader?): MutableList<T> {
if (reader?.peek() === JsonToken.NULL) {
reader.nextNull()
return ArrayList()
}
return delegate?.read(reader) ?: ArrayList()
}
}
// Imports
@Module
class NetModule() {
@Provides
@Singleton
fun provideGson(): Gson {
return GsonBuilder()
.registerTypeAdapterFactory(NullToEmptyAdapterFactory())
.create()
}
// other provides
// ...
}
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
@Suppress("UNCHECKED_CAST")
internal class NullToEmptyAdapterFactory : TypeAdapterFactory {
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
val delegate = gson.getDelegateAdapter(this, type)
val rawType = type.rawType as? Class<T>
return when (rawType) {
String::class.java -> {
StringTypeAdapter() as? TypeAdapter<T>
}
List::class.java -> {
val mutableListDelegate = delegate as? TypeAdapter<MutableList<Any>>
MutableListTypeAdapter(mutableListDelegate) as? TypeAdapter<T>
}
else -> {
null
}
}
}
}
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException
class StringTypeAdapter : TypeAdapter<String>() {
@Throws(IOException::class)
override fun read(reader: JsonReader): String {
if (reader.peek() === JsonToken.NULL) {
reader.nextNull()
return ""
}
return reader.nextString()
}
@Throws(IOException::class)
override fun write(writer: JsonWriter, value: String?) {
if (value == null) {
writer.nullValue()
return
}
writer.value(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment