Is there a way to provide a default type for a lis...
# serialization
s
Is there a way to provide a default type for a list of polymorphic types on the type declaration level (e.g. something akin to how
@JsonClassDiscriminator
makes class discriminators more customizable)? Sample code in thread.
Copy code
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

fun main() {
  val jsonString = """
    {
      "items": [
        { "type": "foo" },
        { "type": "bar" },
        { "type": "baz" } // <- fails due to unknown class discriminator 'baz'
      ]
    }
  """

  Json.decodeFromString<Response>(jsonString)
}

@Serializable
data class Response(val items: List<Item>)

@Serializable
sealed class Item

@Serializable
@SerialName("foo")
object Foo : Item()

@Serializable
@SerialName("bar")
object Bar : Item()

@Serializable
object Unknown : Item() // would like this as the default
d
Nope, it has to go in the module.
s
I see. That's unfortunate, since our
Json
is configured in a separate Gradle module and doesn't know anything about the classes in question. 🤔
d
You can combine `SerializerModule`s btw.
So you define one in this module and use in the module that configures your Json instance.
s
Right, but the Gradle module that configures our
Json
doesn't know about any module that knows about our
@Serializable
types. So unless I can define it in the (let's call it) :json-configuration module and then _alter the
SerializerModule
after the fact in my :module-with-types, I don't see how that would work. Or did I completely misunderstand what you meant, perhaps?
d
Ah I see. I didn't know about the dependency order.
Most I can say is that you shouldn't be defining your
Json
instance in such a low level library then. It should be up to the application. Thought one can always extend it.
Json(YourJson) { serializerModule += ExtraModule }
s
Yeah, I'm thinking about maybe moving it to the application level because of this now. We had originally planned to move it out of our code base (for sharing between multiple projects using the same networking and serialization configuration at a later stage), which makes it seem counter-intuitive to move it to the application module, but, as you say, one can always extend it, which makes it more feasible. 👍
Thanks a lot for your response! simple smile
Although I'm kinda contemplating making a feature request for an annotation-based approach for this. It does feel more intuitive to declare this along with the polymorphic type declarations.
d
Would be interesting to see how that would interact with the runtime module. Maybe a sealed class with one of the subclasses marked as a default would work better.
s
Indeed, something like that would be nice, I think. 👍