Polymorphic serialization: properties named "type" are not serialized with a unique key
See original GitHub issueDescribe the bug
When using the polymorphic serializer, if a class has a property called type
, it will be serialized with two keys called type
– one with the class name, and one with the value of the class property.
To Reproduce
class SampleTests {
@Serializable
abstract class Base
@Serializable
data class Derived(val type: String) : Base()
@Test
fun test() {
val j = Json {
serialModule = SerializersModule {
polymorphic(Base::class) {
addSubclass(Derived.serializer())
}
}
}
val derived = Derived("string")
val stringified = j.stringify(Base.serializer(), derived)
val parsed = j.parse(Base.serializer(), stringified) // throws
assertEquals(
derived,
parsed
)
}
}
Expected behavior
An error should be emitted that the key type
is reserved, with instructions to use SerialName
. It could also be useful to allow the discriminator property name to be configurable
Environment
- Kotlin version: [1.3.30]
- Library version: [0.11.0]
- Kotlin platforms: [e.g. JVM, JS, and Native]
- Gradle version: [e.g. 5.4]
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:6 (2 by maintainers)
Top Results From Across the Web
Deserializing polymorphic types with Jackson based on the ...
You could write a custom deserializer that uses @JsonSubTypes ' "name" and "value" properties in a non-standard way to accomplish what you want....
Read more >How to serialize properties of derived classes with System ...
In this article. Serialize properties of derived classes; Polymorphic type discriminators; Configure polymorphism with the contract model ...
Read more >SerialDescriptor - Kotlin
The structure of the serializable type is not only the property of the type, ... Serial descriptor is identified by its name and...
Read more >Serialization Tutorial - GitHub Pages
This section of the C# Driver Tutorial discusses serialization (and deserialization) of ... To not serialize default values using attributes write:
Read more >User Guide Genson - Fast and easy to use Java and Scala to ...
During serialization if there is no type information available (meaning it is Object), Genson will use the runtime type of the object to...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Discriminator name is configurable, see in
JsonConfiguration
classNow sealed classes are supported automatically and there is the same problem:
The output: