https://kotlinlang.org logo
#serialization
Title
# serialization
t

thevery

10/17/2018, 1:46 PM
Am I right that
@Polymorphic
doesn't work with generics well?
Copy code
class ParserTest {
    open class Field

    @Serializable data class FieldB(val a: String, val b: Int) : Field()

    @Serializable data class FieldC(val a: String, val b: Int) : Field()

    @Serializable data class Data(@Polymorphic val a: List<Field>)

    @Test
    fun testPoly() {
        val obj = JSON.parse<Data>("""{"a":[{a:"a", b: 1}]}""")
        println("obj = ${obj}")
    }
}
produces
java.lang.IllegalArgumentException: JSON at 6: Expected '[, kind: kotlinx.serialization.UnionKind$POLYMORPHIC@33e5ccce'
s

sandwwraith

10/17/2018, 2:45 PM
There’s no type information provided in your input. It is recorded in form [“fqClassName”, class_body], so input should look like
"""{"a":[["FieldC", {a:"a", b: 1}]]}"""
Also, I believe definition should be
val a: List<@Polymorphic Field>
, but it doesn’t matter for now
t

thevery

10/17/2018, 2:51 PM
ic, thank you. Is there any simple way to provide such info without writing full serializer? I need to distinguish
{"a":[{a:"a", b: 1}]}
and
{"a":[{a:"a", c: "1"}]}
s

sandwwraith

10/17/2018, 2:55 PM
I’m afraid not, you need to peek in data before making decision, and this is not what abstract codegen mechanism can do
5 Views