gts13
06/26/2023, 6:22 PM{
"header" : {...},
"sources:": [
{
"discriminator" : "facebook",
"facebook" : {
"common" : {
"lastUsedOn" : "2023-01-01T00:00:00Z"
"device" : "computer"
},
"friends" : [...]
}
},
{
"discriminator" : "facebook",
"facebook" : {
"common" : {
"lastUsedOn" : "2022-01-01T00:00:00Z"
"device" : "mobile"
},
"friends" : [...]
}
},
{
"discriminator" : "instagram",
"instagram" : {
"common" : {
"lastUsedOn" : "2000-01-01T00:00:00Z"
"device" : "tablet"
},
"followers" : [...]
}
},
{
"discriminator" : "twitter",
"twitter" : {
"common" : {
"lastUsedOn" : "2000-01-01T00:00:00Z"
"device" : "mobile"
},
"tweets" : [...]
}
}
]
}
and my data classes are the following:
Serializable
data class User(
@SerialName("header")
private val header: Header,
@SerialName("sources")
private val Sources: List<Source>,
)
@Serializable
sealed class Source {
@SerialName("common")
abstract val common: Common
@Serializable
data class Common(
@SerialName("lastUsedOn")
var lastUsedOn: Instant,
@SerialName("device")
var device: String
)
}
@Serializable
@SerialName("facebook")
data class Facebook(
override val common: Common,
@SerialName("friends")
val friends: ...
) : Source()
@Serializable
@SerialName("instagram")
data class Instagram(
override val common: Common,
@SerialName("followers")
val followers: List<...>
) : Source()
@Serializable
@SerialName("twitter")
data class Twitter(
override val common: Common,
@SerialName("tweets")
val tweets: List<...>
) : Source()
Obviously this fails because of the discriminator
. Is there an elegant way where I can serialize/deserialize given these data classes? Or must I follow another different approach?chr
06/26/2023, 6:34 PMval json = Json {
classDiscriminator = "discriminator"
}
val user: User = json.decodeFromString(myJsonString)
gts13
06/26/2023, 6:40 PMPolymorphic serializer was not found for missing class discriminator ('null')
Source
does not contain the discriminator
val or am I mistaken?Source
objectgts13
06/26/2023, 6:43 PMgts13
06/26/2023, 6:54 PMephemient
06/26/2023, 6:57 PM@Serializable
data class SourceSurrogate(
val discriminator: String,
val facebook: Facebook? = null,
val instagram: Instagram? = null,
val twitter: Twitter? = null,
)
which you then either map manually or use https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#composite-serializer-via-surrogate ongts13
06/29/2023, 8:22 AM