Код: Выделить всё
val str1 = """{"key":"123"}"""
Gson().fromJson(str1, intMapType) // throws an Exception
val str2 = """{"key":123}"""
Gson().fromJson(str2, intMapType) // returns valid Map
Код: Выделить всё
private class StrictIntDeserializer : JsonDeserializer {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Int {
if (!json.isJsonPrimitive || !json.asJsonPrimitive.isNumber) {
throw JsonParseException("Expected Int but got: $json")
}
return json.asInt
}
}
private class StrictStringDeserializer : JsonDeserializer {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): String {
if (!json.isJsonPrimitive || !json.asJsonPrimitive.isString) {
throw JsonParseException("Expected String but got: $json")
}
return json.asString
}
}
private val gson = GsonBuilder()
.registerTypeHierarchyAdapter(Int::class.java, StrictIntDeserializer())
.registerTypeHierarchyAdapter(String::class.java, StrictStringDeserializer())
.create()
Подробнее здесь: https://stackoverflow.com/questions/796 ... ly-in-gson