I am trying to convert this Java sample into Kotlin:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, new JsonStrictBooleanDeserializer())
.registerTypeAdapter(boolean.class, new JsonStrictBooleanDeserializer())
.create();
val gson = GsonBuilder()
.registerTypeAdapter(Boolean::class.java, JsonStrictBooleanDeserializer())
.registerTypeAdapter(Boolean::class.javaPrimitiveType, JsonStrictBooleanDeserializer())
.create()
However, they do not appear to behave the same. I decompiled the Kotlin sample and it appears that only one type adapter is being registered:
(new GsonBuilder())
.registerTypeAdapter((Type)Boolean.TYPE, new JsonStrictBooleanDeserializer())
.registerTypeAdapter((Type)Boolean.TYPE, new JsonStrictBooleanDeserializer())
.create();
What is the correct way of registering a type adapter for boxed and primitive booleans in Kotlin?
Both uses of the Boolean class you have are being compiled to the primitive boolean type. You need to use javaObjectType in addition to javaPrimitiveType, like so:
val gson = GsonBuilder()
.registerTypeAdapter(Boolean::class.javaObjectType, JsonStrictBooleanDeserializer())
.registerTypeAdapter(Boolean::class.javaPrimitiveType, JsonStrictBooleanDeserializer())
.create()
This will result in the first call using Boolean.class and the second using Boolean.TYPE (the Class for the primitive boolean).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With