Skip to content

Commit

Permalink
Create an implementation that allows automatically registering the se…
Browse files Browse the repository at this point in the history
…aled children of a class for polymorphic serialization of a shared (non-sealed) type.
  • Loading branch information
pdvrieze committed Oct 11, 2023
1 parent a675cb3 commit c3f15a5
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public class SealedClassSerializer<T : Any>(
}
}

private val class2Serializer: Map<KClass<out T>, KSerializer<out T>>
internal val class2Serializer: Map<KClass<out T>, KSerializer<out T>>
private val serialName2Serializer: Map<String, KSerializer<out T>>

init {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ public class PolymorphicModuleBuilder<in Base : Any> @PublishedApi internal cons
private var defaultSerializerProvider: ((Base) -> SerializationStrategy<Base>?)? = null
private var defaultDeserializerProvider: ((String?) -> DeserializationStrategy<Base>?)? = null

/**
* Registers the subclasses of the given class as subclasses of the outer class. Currently this requires `baseClass`
* to be sealed.
*/
public fun <T: Base> subclassesOf(baseClass: KClass<T>, serializer: KSerializer<T>) {
require(serializer is SealedClassSerializer) {
"subClassesOf only supports automatic adding of subclasses of sealed types."
}
for ((subsubclass, subserializer) in serializer.class2Serializer.entries) {
@Suppress("UNCHECKED_CAST")
// We don't know the type here, but it matches if correct in the sealed serializer.
subclass(subsubclass as KClass<T>, subserializer as KSerializer<T>)
}
}

/**
* Registers a [subclass] [serializer] in the resulting module under the [base class][Base].
*/
Expand Down Expand Up @@ -116,3 +131,15 @@ public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.
*/
public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclass(clazz: KClass<T>): Unit =
subclass(clazz, serializer())

/**
* Registers the child serializers for the sealed [subclass] [serializer] in the resulting module under the [base class][Base].
*/
public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclassesOf(serializer: KSerializer<T>): Unit =
subclassesOf(T::class, serializer)

/**
* Registers the child serializers for the sealed class [T] in the resulting module under the [base class][Base].
*/
public inline fun <Base : Any, reified T : Base> PolymorphicModuleBuilder<Base>.subclassesOf(clazz: KClass<T>): Unit =
subclassesOf(clazz, serializer())
5 changes: 5 additions & 0 deletions docs/polymorphism.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,11 @@ fun main() {

> Note: On Kotlin/Native, you should use `format.encodeToString(PolymorphicSerializer(Project::class), data))` instead due to limited reflection capabilities.
### Registering sealed children as subclasses
A sealed parent interface or class can be used to directly register all its children using subclassesOf. This will
expose all children that would be available when serializing the parent directly, but now as sealed. Please note that
this is will remain open serialization, and the sealed parent serializer will not be used in serialization.

<!--- TEST LINES_START -->

### Property of an interface type
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.features

import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.*
import kotlinx.serialization.test.assertStringFormAndRestored
import kotlin.test.Test

class PolymorphicSealedChildTest {

@Serializable
data class FooHolder(
val someMetadata: Int,
val payload: List<@Polymorphic FooBase>
)

@Serializable
abstract class FooBase

@Serializable
@SerialName("Foo")
sealed class Foo: FooBase() {
@Serializable
@SerialName("Bar")
data class Bar(val bar: Int) : Foo()
@Serializable
@SerialName("Baz")
data class Baz(val baz: String) : Foo()
}

val sealedModule = SerializersModule {
polymorphic(FooBase::class) {
subclassesOf(Foo.serializer())
}
}

val json = Json { serializersModule = sealedModule }

@Test
fun testSaveSealedClassesList() {
assertStringFormAndRestored(
"""{"someMetadata":42,"payload":[
|{"type":"Bar","bar":1},
|{"type":"Baz","baz":"2"}]}""".trimMargin().replace("\n", ""),
FooHolder(42, listOf(Foo.Bar(1), Foo.Baz("2"))),
FooHolder.serializer(),
json,
printResult = true
)
}

@Test
fun testCanSerializeSealedClassPolymorphicallyOnTopLevel() {
assertStringFormAndRestored(
"""{"type":"Bar","bar":1}""",
Foo.Bar(1),
PolymorphicSerializer(FooBase::class),
json
)
}
}

0 comments on commit c3f15a5

Please sign in to comment.