Hi.. I wanted to know how to serialize a json gene...
# serialization
s
Hi.. I wanted to know how to serialize a json generic property whose type is known only at runtime. Eg:
Copy code
"response":{
"value":5
}"
Value can be Int or string or a list of some other type.
s
This is what I’m doing
Copy code
@Serializable
data class Response (
  val value : Value? = null
)

@Serializable(with = ValueSerializer::class)
sealed class Value{
  @Serializable
  data class OptionArrayValue(val value: List<Option>): Value()
  @Serializable
  data class IntegerValue(val value: Int): Value()
  @Serializable
  data class StringValue(val value: String): Value()
}


object ValueSerializer : JsonContentPolymorphicSerializer<Value>(Value::class) {
  override fun selectDeserializer(element: JsonElement) = when {
    element is JsonPrimitive -> {
       if(element.content is String){
         Value.StringValue.serializer()
       } else {
         Value.IntegerValue.serializer()
       }
    }
    else -> Value.OptionArrayValue.serializer()
  }
}
However, I’m getting the error
kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject (Kotlin reflection is not available) as the serialized body of shared.features.mainFeed.entities.Value.StringValue, but had class kotlinx.serialization.json.JsonLiteral (Kotlin reflection is not available)
Am I doing something wrong? @sandwwraith