Kotlinx.serialization: Serializing open classes results into unexpected json

Created on 14 Dec 2017  路  4Comments  路  Source: Kotlin/kotlinx.serialization

The output of the code below seems wrong. (The output is inlined as comments) The problem is in the boxed case were the class name is serialized along with the class. This is with version 0.3.

The same issue persist with all classes derived from BaseClass.

@Serializable
open class BaseClass(val base: Int = 0)

@Serializable
class Box(val baseClass: BaseClass)

@Test
fun testSerializable() {
    val jsonBaseClass = JSON.stringify(BaseClass())
    // Result (ok): {"base":0}
    val json = JSON.stringify(Box(BaseClass()))
    // Result (!!): {"baseClass":["org.fejoa.SerializableTest.BaseClass",{"base":0}]}
}
design

Most helpful comment

Interfaces should solve your problem

All 4 comments

Yes, that's how a polymorphic serialization works for open classes - framework record object type along with the object itself. However, due to serializers static resolving problems at call site, this behaviour is different for nested and root-level classes. You can either specify that you want to record type explicitly by using PolymorphicSerializer in call to JSON.stringify, or suppress it in Box by using @Serializable(with=...) on field baseClass

NB: this mechanism is under design now, and later type recording may be disabled by default. Feel free to describe here expected behaviour, so we can collect maximum use-cases

My main purpose was data serialization and I simply wanted to unify similar objects (objects that have the same variables). For this reason it was unexpected to have the type information in the output.

Interfaces should solve your problem

Now polymorphic serialization enables automatically only on interfaces and abstract classes, open classes are serialized as usual.

Was this page helpful?
0 / 5 - 0 ratings