Any values when use @Polymorphic #272
-
I have test to parse as following: import kotlinx.serialization.Polymorphic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.serializer
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.serialization.XmlElement
import nl.adaptivity.xmlutil.serialization.XmlSerialName
import nl.adaptivity.xmlutil.serialization.XmlValue
private val module = SerializersModule {
polymorphic(Any::class) {
subclass(Order1::class, serializer())
subclass(StopOrder1::class, serializer())
subclass(String::class, String.serializer())
}
}
private val parser = XML(module) {
autoPolymorphic = true
}
interface XmlEntity
@Serializable
data class Orders1(@XmlValue var orders: List<@Polymorphic Any>) : XmlEntity
@Serializable
@XmlSerialName("order")
data class Order1(
@SerialName("transactionid") val transactionId: String,
@XmlElement @SerialName("secid") val secId: String,
) : XmlEntity
@Serializable
@XmlSerialName("stoporder")
data class StopOrder1(
@SerialName("transactionid") val transactionId: String,
@XmlElement @SerialName("secid") val secId: String,
) : XmlEntity
@Serializable
@SerialName("stoploss")
data class StopLoss(
@SerialName("usecredit") val useCredit: String,
@XmlElement @SerialName("activationprice") val activationPrice: Double,
@XmlElement val quantity: Int,
@XmlElement @SerialName("bymarket") val byMarket: Boolean
) : XmlEntity
val xml = """<orders>
<order transactionid="32021651">
<secid>8135</secid>
</order>
<stoporder transactionid="20105503">
<secid>8135</secid>
</stoporder>
<stoporder transactionid="31465073">
<secid>8135</secid>
</stoporder>
</orders>"""
fun main() {
val decoded = parser.decodeFromString(serializer<Orders1>(), xml)
println("size " + decoded.orders.size)
println(decoded)
} It deserializes correctly, but extra string elements are added to the result, such as empty lines with carriage returns.
simple and working option to filter by interface, but maybe there is a more correct way ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
In this case you don't want to use To explain a bit, what |
Beta Was this translation helpful? Give feedback.
@auzatsepin Note that for this case the best approach is to not use
@XmlValue
. As an aside the@XmlValue
case also has a cache key issue if the same list is also used in the same format instance without the value (fixed in the dev branch) - only relevant for string elements (in case they are in a list in an xmlValue they are captured by in place strings, without the value annotation they are wrapped in a<xsd:string>
element..