sindrenm
01/04/2022, 5:30 PM@JsonClassDiscriminator
makes class discriminators more customizable)? Sample code in thread.sindrenm
01/04/2022, 5:30 PMimport 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
Dominaezzz
01/04/2022, 5:51 PMsindrenm
01/05/2022, 8:59 AMJson
is configured in a separate Gradle module and doesn't know anything about the classes in question. 🤔Dominaezzz
01/05/2022, 9:01 AMDominaezzz
01/05/2022, 9:01 AMsindrenm
01/05/2022, 9:06 AMJson
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?Dominaezzz
01/05/2022, 9:07 AMDominaezzz
01/05/2022, 9:09 AMJson
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 }
sindrenm
01/05/2022, 9:15 AMsindrenm
01/05/2022, 9:16 AMsindrenm
01/05/2022, 9:17 AMDominaezzz
01/05/2022, 9:19 AMsindrenm
01/05/2022, 9:29 AM