kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Swift-style sum/union/variant encoding

Open dpwiz opened this issue 2 years ago • 2 comments

I'm trying to shuttle data between iOS app in Swift and Kotlin apps.

Kotlinx.serialization uses tag field for this:

[ {"type": "this", "field1": "value1"}
, {"type": "that"} // no constructor args
, {"type": "thaz"} // same as above
]

Swift (and some APIs) use single-field object wrapper for tagging:

[ {"this": {"field1": "value1"}}
, "that": {} // no constructor args
, "thaz" // short form for the previous one
]

I'd like an option to switch encoding to the single-field-wrapper (with an optional tag shortcut). Otherwise I'd have to abandon generic serialization for my huge sum types and do it manually (:cold_sweat:).

dpwiz avatar Sep 27 '23 13:09 dpwiz

Unfortunately, we don't have such an option at the moment. It seems that this format is rare ( as there aren't similar feature requests), so we can't promise we'll implement it. You can make desired transformations after serializing your sum types with the default serializer with JsonTransformingSerializer (https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#json-transformations)

sandwwraith avatar Oct 10 '23 14:10 sandwwraith

This format is also the default format used by Rust's main serialization library, serde. They call this representation "externally tagged". This style is less natural when working directly on the data, but it has the benefit of guaranteeing an absence of conflict between the tag and content.

This means that this representation is ideal if you care more about reliability than a "nice" schema.

demurgos avatar Jan 15 '24 16:01 demurgos