question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Polymorphic serializer, ignore unregistered objects when deserializing list of polymorphic objects

See original GitHub issue

I have made a serializer class for the json:api specificaiton.

@Serializable
data class JsonApiResponseItem(
        override val jsonapi: JsonApiVersion,
        override val included: List<@Polymorphic JsonApiObject>? = null,
        @Polymorphic val data: JsonApiObject): JsonApiResponse() {

}

included can return many different types of objects which I am successfully using the polymorphic feature to deserialize. But this only works if all possible object types are registered in the scope of class JsonApiObject for polymorphic serialization.

If any types are not registered an error like is thrown

io.ktor.client.call.ReceivePipelineException: Fail to run receive pipeline: 
kotlinx.serialization.SerializationException: example-type is not registered for polymorphic 
serialization in the scope of class api.jsonapi.JsonApiObject

Is it possible to ignore deserializing polymorphic type objects which are not registered for polymorphic serialization without throwing an error? This would really be helpful because it would prevent deserialization from throwing errors if any new objects added to the included list… and it would be convenient if don’t actually need to deserialize some of the included objects

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:6
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

5reactions
luca992commented, May 16, 2019

Yeah, that sounds right. Maybe another option would be to allow this in nonstrict mode by allowing a backup serializer to be registered for polymorphic classes in SerializersModule.

maybe something along the lines of:

@Serializable
data class EmptyJsonApiObject : JsonApiObject()

Json(context = SerializersModule {
    polymorphic(JsonApiObject::class) {
        JsonApiObjectUser::class with JsonApiObjectUser.serializer()
        JsonApiObjectEmployee::class with JsonApiObjectEmployee.serializer()
        addBackUpSerializer(EmptyJsonApiObject.serializer())
    }
},
        configuration = JsonConfiguration(
                strictMode = false,
        )
)

//addBackUpSerializer would require EmptyJsonApiObject to extend JsonApiObject

So in nonStrict mode at least, instead of throwing kotlinx.serialization.SerializationException: example-type is not registered for polymorphic serialization in the scope of class api.jsonapi.JsonApiObject, it would attempt to de-serialize using EmptyJsonApiObject’s deserializer. Which I think should work fine, because nonStrict allows deserializing to an empty class.

My suggestion sounds pretty hacky though. But might be something to consider until support for skipping malformed element can be added.

3reactions
ge-orgcommented, Jan 9, 2022

I know this issue is pretty old by now, however, I just stumbled upon it since I had the same problem. There’s another solution available that doesn’t require a wrapper or custom serializer.

We can register a default serializer for polymorphic types that will be used as a fallback. The downside compared to the wrapper solution is that we must register the serializer for every new polymorphic type we add. So it requires some discipline.

val json = Json {
    serializersModule += SerializersModule {
        polymorphic(MyPolymorphicType::class) {
            defaultDeserializer { MyPolymorphicType.Unknown.serializer() }
        }
    }
}

https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#default-polymorphic-type-handler-for-deserialization

Read more comments on GitHub >

github_iconTop Results From Across the Web

Kotlin Serialization issues: Class is not registered for ...
SerializationException: Class 'CustomConvertible' is not registered for polymorphic serialization in the scope of 'Convertible'.
Read more >
JSON serialization - Immutables
When type adapters are not registered, Gson will use default reflective serializer. However, it will fail to deserialize! There's the potential to confuse...
Read more >
Serialization - Special Considerations - Boost C++ Libraries
Next time an object of that class is serialized in that same archive, this number is ... Polymorphic pointers of derived classes may...
Read more >
DataMapper on CocoaPods.org
DataMapper is a framework for safe deserialization/serialization of objects from/to different data representation standards (as of now we support JSON but ...
Read more >
Kryo (Kryo 5.1.1 API) - javadoc.io
Maps classes to serializers so object graphs can be serialized automatically. ... Resets object graph state: unregistered class names, references to ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found