Hi, I have a very weird bug that I've never got be...
# serialization
a
Hi, I have a very weird bug that I've never got before when trying to serialize something :
Copy code
val value: HeightProvider = ConstantHeightProvider(Absolute(10))
jsonEncoder.encodeToString(value) assertsIs """
	{
		"absolute": 10
	}
""".trimIndent() // this is what I'm waiting for
And this is what I get :
Copy code
{
  "type": "kotlin.collections.LinkedHashMap",
  "absolute": 10
}
Here is my code :
Copy code
@Serializable(with = ConstantHeightProvider.Companion.ConstantSerializer::class)
data class ConstantHeightProvider(
	var value: HeightConstant,
) : HeightProvider() {
	companion object {
		object ConstantSerializer : KSerializer<ConstantHeightProvider> {
			override val descriptor = buildClassSerialDescriptor("constant")

			override fun deserialize(decoder: Decoder) = error("Constant cannot be deserialized")

			override fun serialize(encoder: Encoder, value: ConstantHeightProvider) {
				require(encoder is JsonEncoder) { "ConstantHeightProvider can only be serialized to Json" }
				val value = encoder.json.encodeToJsonElement(HeightConstant.serializer(), value.value)
				println(value) // I correctly get {"absolute":10}
				encoder.encodeJsonElement(value)
			}
		}
	}
}

// I've tried also with this and the same issue appears
@Serializable
value class ConstantHeightProvider(
	val value: HeightConstant,
) : HeightProvider
How can I fix this issue ? I don't have any clue right now Know that serializing a
HeightConstant
directly results in no issue
e
Not sure if it is only test or also production code will have it
You are using polymorphism
And that call will put type discriminator in the json
I think you can or disable put discriminator in json in general
To fix the test you should call
encode
variant with serializer as parameter
a
I have a custom serializer for
HeightConstant
which removes the
type
property, but what bothers me is that, why do I get this weird value ? This is not what I'm expecting at all. Also it works inside the
ConstantSerializer
, but the resulting value (which is just copied from
HeightConstant
serializer) isn't the same at all ? Why
kotlin.collections.LinkedHashMap
🤔 ?
e
Sorry, no idea