Help with implementing kotlinx-serialization custom formats with named values

Hi all,

I’m currently trying to implement a new custom serialization format for kotlinx-serialization. That format has:

  • Named values
  • type annotations
  • both a binary and a string representation

(Weird combination, I know… If you’re interested, look up “NBT format”, you might already know it)

One substantial goal of the library was to provide a standalone DSL for accessing values and building tree-like structures that can be decoded. Therefore, the entire encoding / decoding part was already done by me. Now the only thing left to do is to integrate that part with the Encoder / Decoder interfaces.

And that part confuses me a lot. I’m already stuck with implementing Encoder / CompositeEncoder. From my research, the basic interfaces are best suited for sequential encoding / decoding. Most examples of named-value formats I researched (JSON, Properties, …) make use of an internal class called NamedValueEncoder(). The documentation marks this class as an internal API and it is discouraged to extend it.

I’m still struggling to understand the basic process of encoding (and later, decoding) a named-value format using the Encoder / CompositeEncoder interfaces, because the functions do not provide names for the names to be encoded.

So, basically, to break down my question to the core: How would you implement Encoder / CompositeEncoder to store the encoded values in a key/value nested map? For example, a structure like this (given in JSON):

{
    "first": 1,
    "second": "Hello, World!",
    "third": {
         nested: 1.2
    }
}

Should be encoded to a map structure like

map["first"] -> 1
map["second"] -> "Hello, World!"
map["third"] ->
    third["nested"] -> 1.2

Any help would be greatly appreciated. Thank you!