-
I'm wondering if there is a nice way to deal with inheritance when deserialising. Not sure if I have missed something here or not. The following is 2 classes that are mostly the same but each have one unique property. This deserialises correctly. val dogXML ="""
<dog id="111">
<age>12</age>
<title>
<text locale="en-GB"><![CDATA[dog_title_en_gb]]></text>
<text locale="en-GB"><![CDATA[dog_title_fr_fr]]></text>
</title>
<bark>dog_test</bark>
</dog>
""".trimIndent()
val catXML ="""
<dog id="222">
<age>8</age>
<title>
<text locale="en-GB"><![CDATA[cat_title_en_gb]]></text>
<text locale="en-GB"><![CDATA[cat_title_fr_fr]]></text>
</title>
<meow>cat_test</meow>
</dog>
""".trimIndent()
@Serializable
class Dog(
val id: String,
@XmlElement(true)
val age: Int,
@XmlSerialName(value = "title")
@XmlChildrenName(value = "text")
val titles: List<LocalisedTitle>,
@XmlElement(true)
val bark: String,
)
@Serializable
class Cat(
val id: String,
@XmlElement(true)
val age: Int,
@XmlSerialName(value = "title")
@XmlChildrenName(value = "text")
val titles: List<LocalisedTitle>,
@XmlElement(true)
val meow: String,
)
@Serializable
class LocalisedTitle(
@XmlElement(false) val locale:String,
@XmlValue(true) val value: String
)
If you want to move the common properties to a base type, I'm not sure if there is a neat way to do that? The following works, but now the properties in the base type must have default values, which is not ideal. @Serializable
open class Animal(
val id: String? = null,
@XmlElement(true)
val age: Int = 0,
@XmlSerialName(value = "title")
@XmlChildrenName(value = "text")
val titles: List<LocalisedTitle> = emptyList(),
)
@Serializable
class Dog(
@XmlElement(true)
val bark: String
): Animal()
@Serializable
class Cat(
@XmlElement(true)
val meow: String
): Animal()
@Serializable
class LocalisedTitle(
@XmlElement(false) val locale:String,
@XmlValue(true) val value: String
) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The way to do this is for the base class to not have a primary constructor at all (that way the serialization plugin can generate a constructor for its own use). |
Beta Was this translation helpful? Give feedback.
The way to do this is for the base class to not have a primary constructor at all (that way the serialization plugin can generate a constructor for its own use).