Ayfri
07/16/2023, 12:09 AMelements = listOf("test")
it will only be serialized as "elements": "test"
but if I have elements = listOf("foo", "bar")
then it will be serialized as "elements": ["foo", "bar"]
Javier
07/16/2023, 12:24 AMsealed interface Foo
data class Bar(val elements: String) : Foo
data class Baz(val elements: List<String>) : Foo
Adam S
07/16/2023, 8:29 AMAdam S
07/16/2023, 8:38 AM@Serializable
classes
typealias InlinableList<T> = @Serializable(with = InlinableListSerializer::class) List<T>
@Serializable
data class MyJsonData(
val strings: InlinableList<String>,
val integers: InlinableList<Int>,
)
Then you just need to create the InlinableListSerializer:
class InlinableListSerializer<T>(
elementSerializer: KSerializer<T>
) : KSerializer<List<T>> {
// ...
}
Because InlinableList has a generic type the constructor for InlinableListSerializer must have a single parameter for the serializer for T
, which you can use in the serialize()
/ deserialize()
functions.
You’ve mentioned in your other messages that you’re only interested in deserializing, so I’ll just create a quick demo for that:
override fun deserialize(decoder: Decoder): List<T> {
require(decoder is JsonDecoder) { "only JSON is supported" }
val element = decoder.decodeJsonElement()
return when (element) {
is JsonPrimitive -> {
val single = TODO("deserialize a single element using elementSerializer")
listOf(single)
}
is JsonArray -> {
TODO("deserialize a using ListSerializer(elementSerializer)")
}
else -> error("unsupported JSON element $element")
}
)
Ayfri
07/16/2023, 9:02 AMAdam S
07/16/2023, 9:03 AMAyfri
07/16/2023, 9:05 AM