Skip to content

Polymorphic Serialization fails with Class 'ArrayList' is not registered for polymorphic serialization in the scope of 'Collection' #1946

@abhishiv

Description

@abhishiv

Describe the bug

Hey all, I have been stuck on this for hours. Apparently whenever I try to serialise a polymorphic type inside of a MutableList it fails with

Class 'ArrayList' is not registered for polymorphic serialization in the scope of 'Collection'.
[ERROR] Mark the base class as 'sealed' or register the serializer explicitly.

I just can't figure out the what a serializer for Arraylist in the scope of Collection would look like. I found #1341 but that doesn't look related since I'm trying to serialize an ArrayList of classes not primitives so that should be possible.

To Reproduce
Attach a code snippet or test data if possible.

package test

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
sealed class Item2() {
    // code for eating, talking, walking
}

@Serializable
class Book2(val name: String) : Item2() {
}

@Serializable
class Magazine2(val name: String) : Item2() {
}

@Serializable
class Library2(val name: String ) {
    constructor() : this("Unnamed Library")
    
    @Polymorphic
    val items: MutableCollection<Item2> = mutableListOf()
}

class JSONSerde {

    companion object {
        val json = Json { ignoreUnknownKeys = true; prettyPrint = true; useArrayPolymorphism = true
         }
    }

    inline fun <reified T> serialize(data: T): String = json.encodeToString(data)

    inline fun <reified T> deserialize(string: String) = json.decodeFromString<T>(string)
}

fun main() {
    val library = Library2("My Library");
    library.items.add(Book2("Book 1"));
    library.items.add(Magazine2("Magazine 2"));
    val jsonSerde = JSONSerde()

    val string = jsonSerde.serialize(library)
    println(string)
}

Expected behavior

Environment

  • Kotlin version: [e.g. 1.3.30]: 1.6.10
  • Library version: [e.g. 0.11.0]: 1.3.3
  • Kotlin platforms: [e.g. JVM, JS, Native or their combinations]: JVM

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions