val mapType: Type = object : TypeToken<Map<String, Any>>() {}.type
val listType: Type = object : TypeToken<List<Any>>() {}.type
val gson = GsonBuilder()
.registerTypeAdapter(mapType, CustomizedObjectTypeAdapter())
.registerTypeAdapter(listType, CustomizedObjectTypeAdapter())
.create()
Last active
February 23, 2021 00:24
-
-
Save VincentSit/474cf311eeeab169f0e674f755b33058 to your computer and use it in GitHub Desktop.
Prevent GSON from converting integers to doubles in Kotlin
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
import com.google.gson.Gson | |
import com.google.gson.TypeAdapter | |
import com.google.gson.internal.LinkedTreeMap | |
import com.google.gson.stream.JsonReader | |
import com.google.gson.stream.JsonToken | |
import com.google.gson.stream.JsonWriter | |
import java.io.IOException | |
import java.util.* | |
class CustomizedObjectTypeAdapter : TypeAdapter<Any>() { | |
private val delegate = Gson().getAdapter(Any::class.java) | |
@Throws(IOException::class) | |
override fun write(out: JsonWriter?, value: Any) { | |
delegate.write(out, value) | |
} | |
@Throws(IOException::class) | |
override fun read(`in`: JsonReader): Any? { | |
return when (`in`.peek()) { | |
JsonToken.BEGIN_ARRAY -> { | |
val list: MutableList<Any?> = ArrayList() | |
`in`.beginArray() | |
while (`in`.hasNext()) { | |
list.add(read(`in`)) | |
} | |
`in`.endArray() | |
list | |
} | |
JsonToken.BEGIN_OBJECT -> { | |
val map: MutableMap<String, Any?> = | |
LinkedTreeMap() | |
`in`.beginObject() | |
while (`in`.hasNext()) { | |
map[`in`.nextName()] = read(`in`) | |
} | |
`in`.endObject() | |
map | |
} | |
JsonToken.STRING -> `in`.nextString() | |
JsonToken.NUMBER -> { | |
//return in.nextDouble(); | |
val n: String = `in`.nextString() | |
if (n.indexOf('.') != -1) { | |
n.toDouble() | |
} else n.toLong() | |
} | |
JsonToken.BOOLEAN -> `in`.nextBoolean() | |
JsonToken.NULL -> { | |
`in`.nextNull() | |
null | |
} | |
else -> throw IllegalStateException() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment