Császár Ákos
09/06/2023, 2:08 PM@Serializable
class ResponseData<T>(
@SerialName("executionTime")
val executionTime: Double,
@SerialName("result")
val result: T
)
@Serializable
class LiveAsset : BaseAsset() {}
@Serializable
class MediaAsset : BaseAsset() {}
@Serializable
class ProgramAsset : BaseAsset() {}
@Serializable(with = BaseAssetSerializer::class)
abstract class BaseAsset : BaseResult() {}
@Serializable
abstract class BaseResult: BaseObject {
@SerialName("objectType")
override val objectType: String? = null
}
interface BaseObject {
val objectType : String?
}
when I try to deserialize a http response using json.decodeFromString<ResponseData<ProgramAsset>>(response)
the values from the ProgramAsset are serialized correclty (they contain the correct data), but the values from BaseAsset are not (they will get the default value, in this case null
). Somebody has an idea, what can be the problem? I just left out the values from the subclasses of BaseAsset for simplicity.
My polymorphic serializer looks like this:
object BaseAssetSerializer : JsonContentPolymorphicSerializer<BaseAsset>(BaseAsset::class) {
private const val TYPE_KEY = "objectType"
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<BaseAsset> {
return when (element.jsonObject[TYPE_KEY]?.jsonPrimitive?.contentOrNull) {
KalturaObjectType.ASSET_PROGRAM.value -> ProgramAsset.serializer()
KalturaObjectType.ASSET_MEDIA.value -> MediaAsset.serializer()
KalturaObjectType.ASSET_LIVE.value -> LiveAsset.serializer()
else -> throw UnsupportedOperationException("Unknown polymorphic type")
}
}
}
Adam S
09/06/2023, 2:30 PMCsászár Ákos
09/06/2023, 5:00 PM@Serializable
class LiveAsset : BaseAsset() {
@Serialname("variable1")
val variable1: String? = null //ex. value: "hello"
}
@Serializable(with = BaseAssetSerializer::class)
abstract class BaseAsset : BaseResult() {
@Serialname("variable2")
val variable2: String? = null. //ex. value: "friend"
}
After decoding, the variable1 will have a value which is not the default null value (lets say "hello") , but the variable2 will be null (instead of "friend") which is not right because there is data coming from the backend.
If I don't use a custom Polymorphic serializer, it works, both variables will have the correct value. But sadly I need to use the polymorphic serializer.pdvrieze
09/13/2023, 9:40 AMBaseAssetSerializer
. Custom serializers cannot be inherited. This means you will have to have custom child serializers too if you want their serialization to incorporate the custom parent. I suspect the only reason it compiles is because BaseAsset is actually empty.Császár Ákos
09/13/2023, 9:49 AM