Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register type adapter for boolean.class/Boolean::class.javaPrimitiveType and Boolean.class/Boolean.class.java

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?

like image 555
ordonezalex Avatar asked Sep 17 '25 16:09

ordonezalex


1 Answers

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).

like image 115
apetranzilla Avatar answered Sep 19 '25 08:09

apetranzilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!