0

I've already spent a lot of time trying to write custom serializer, to replace Int (TINYINT from mysql) to Boolean during serialization.

Using Gson I do it without problems, something like this (java):

    public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {

    @Override
    public JsonElement serialize(Boolean arg0, Type arg1, JsonSerializationContext arg2) {
        return new JsonPrimitive(arg0 ? 1 : 0);
    }

    @Override
    public Boolean deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        return arg0.getAsInt() == 1;
    }
}
GsonBuilder().registerTypeAdapter(Boolean.class, serializer)

maybe someone already solved a similar problem using kotlinx.serialization library?

Thank you.

Webdma
  • 714
  • 6
  • 16

1 Answers1

0

Most likely this is not possible :( the only solution that I found:

  1. making custom "BooleanWraper"
  2. override serializer methods "save" and "load"
  3. use "BooleanWraper" instead of Boolean

    @Serializable
    data class BooleanWraper(val value: Boolean){
    
    @Serializer(forClass = BooleanWraper::class)
    companion object : KSerializer<BooleanWraper> {
        override fun save(output: KOutput, obj: BooleanWraper) =
            output.writeIntValue(if (obj.value) 1 else 0)
    
        override fun load(input: KInput): BooleanWraper=
            BooleanWraper(input.readNullable(IntSerializer) == 1)
    }
    

    }

Using wraper:

@Serializable
data class Example(
    @SerialName("my_bool") val myBool: BooleanWraper
)
Webdma
  • 714
  • 6
  • 16