https://kotlinlang.org logo
#serialization
Title
# serialization
a

Ayfri

03/11/2023, 10:43 PM
Hi, I have a very weird problem where when I try to serialize a list of elements Predicate with custom serializer, I always get a
"type": "kotlin.collections.ArrayList
even with a custom serializer :
Copy code
object PredicateConditionsSerializer : KSerializer<List<Predicate>> by ListSerializer(Predicate.Companion.Predicate) {
	override fun serialize(encoder: Encoder, value: List<Predicate>) {
		require(encoder is JsonEncoder) { "Predicate can only be serialized with Json" }

		val element = buildJsonArray {
			value.forEach { condition ->
				add(Json.encodeToJsonElement(Predicate.Companion.Predicate, condition))
			}
		}

		encoder.encodeJsonElement(element)
	}
}
Even when
element
is replaced with a simple array of one string :
buildJsonArray { add("test") }
I get this :
Copy code
[
    "type": "kotlin.collections.ArrayList",
    "test"
]
b

Ben Woodworth

03/13/2023, 4:34 AM
I'm suspecting it's some kind of mismatch between the serial descriptor and the way it's being encoded, but it's hard to be sure What happens if instead of delegating to the list serializer, you implement everything like a surrogate serializer, setting the descriptor to JsonArray.serializer().descriptor, and instead of encodeJsonElement, doing encodeSerializableValue(JsonArray.serializer(), element)
11 Views