I have to deserialize 0
to false
and 1
to true
.
I've created this class:
class IntBooleanDeserializer : JsonDeserializer<Boolean?> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Boolean? {
json?.let {
return json.asInt == 1
}
return null
}
}
And registered it:
private val gson = GsonBuilder()
.registerTypeAdapter(Boolean::class.java, IntBooleanDeserializer())
.create()
And created test class for this:
data class BooleanClass(val value: Boolean?)
And then:
gson.fromJson("{\"value\": 0}", BooleanClass::class.java)
This code throws exception:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a boolean but was NUMBER at line 1 column 12 path $.value
Seems that Gson does not use my deserializer for Boolean?
, but successfully uses other custom deserializers for other types (for example, for enums).
Why?