0

I would like to make a Kotlin class serializable using Kotlin serialization.

The class is very simple, something like this:

@Serializable(with = CustomSerializer::class)
data class MyObject(val keys: Set<String>)

Now, I need the serialization format to be a JSON object where the keys are given by the Set<String> and the values are always empty JSON objects.

Example:

val example = MyObject(setOf("abc", "def"))

Should serialize to:

{ "abc": {}, "def": {} }

The reason is that this object is being sent to an API where that's how they want the JSON to look like... the empty objects could contain some directives but I don't want or need to use those.

Having trouble doing that by just reading the documentation.

1 Answer 1

1

I've found one way to do it... and it seems simple enough!

I realized that I can get a serializer of empty Objects almost for free with this:

@Serializable
private object EmptyMap

Now, I can write a custom serializer in a straightforward way:

object MyObjectSerializer : KSerializer<MyObject> {
    private val _delegate = MapSerializer(String.serializer(), EmptyMap.serializer())

    override val descriptor: SerialDescriptor = _delegate.descriptor

    override fun serialize(encoder: Encoder, value: MyObject) {
        val data = value.keys.associateWith { EmptyMap }
        encoder.encodeSerializableValue(_delegate, data)
    }

    override fun deserialize(decoder: Decoder): MyObject {
        val value = decoder.decodeSerializableValue(_delegate)
        return MyObject(value.keys)
    }

}

Now all that's left to do is to apply the serializer on the type, which can be done with:

@Serializer(with = MyObjectSerializer)
data class MyObject(val keys: Set<String>)

Running Json.encodeToString(example) on the examples works perfectly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.