Ayfri
08/04/2023, 1:07 PMval 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 :
{
"type": "kotlin.collections.LinkedHashMap",
"absolute": 10
}
Here is my 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 issueEugen Martynov
08/04/2023, 3:22 PMEugen Martynov
08/04/2023, 3:22 PMEugen Martynov
08/04/2023, 3:23 PMEugen Martynov
08/04/2023, 3:24 PMEugen Martynov
08/04/2023, 3:24 PMencode
variant with serializer as parameterAyfri
08/05/2023, 3:27 PMHeightConstant
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
🤔 ?Eugen Martynov
08/07/2023, 9:15 AM