Search code examples
kotlingsoncode-conversion

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?


Solution

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