8

How to serialize a library class to Protobuf with kotlinx.serialization? Since it's non-editable, I can't add @SerialId annotations to its properties as instructed in runtime_usage.md#protobuf. If I write my own external serializer as in custom_serializers.md, it doesn't tell me how to specify the SerialIds for Protobuf serialization.

For example, I am trying to serialize a java.math.BigDecimal, storing its unscaledValue as bytes and its scale as sint32. It's easy to do it with the original Protobuf Java library, but I am wondering how to do it with kotlinx.serialization.

Shreck Ye
  • 1,591
  • 2
  • 16
  • 32

1 Answers1

0

You can use contextual serialization for class you have no control over. For example define your serializer like this (json in my case but you get the idea)

val kxJson = Json {
    serializersModule = SerializersModule {
        contextual(java.math.BigDecimal::class, BigDecimalKSerializer)
    }
}

And then implement your BigDecimalKSerializer. In classes where you use BigDecimal you should annotate field with @Contextual.

More details are here.

expert
  • 29,290
  • 30
  • 110
  • 214