Note: This issue is about the kotlinx.serialization generator.
Description
Given the code:
@Serializable
sealed class Parent
@Serializable
data class ChildOne(val text: String)
@Serializable
data class ChildTwo(val number: Int)
val one = ChildOne("some_text")
val two = ChildTwo(123)
There is a difference between serializing one as Parent or as ChildOne:
The field name (here the default - type) can be changed by annotating the parent class with @JsonClassDiscriminator, and the values by annotating the child classes with @SerialName:
@Serializable
@JsonClassDiscriminator("the_type")
sealed class Parent
@Serializable
@SerialName("child_one")
data class ChildOne(val text: String)
@Serializable
@SerialName("child_two")
data class ChildTwo(val number: Int)
The generated schemas do not currently contain the type discriminator field.
Example
Given the data types:
@Serializable
sealed class Response
@Serializable
@SerialName("auth_failed")
data class AuthFailedResponse(
val reason: String,
val description: String,
val scopes: String? = null
) : Response()
@Serializable
@SerialName("success")
data class SuccessfulResponse(val data: Data) : Response()
And the following config (schemas displayed using swagger-ui):
schemas {
generator = { type ->
type
.processKotlinxSerialization()
.connectSubTypes()
.generateSwaggerSchema()
.withAutoTitle(TitleType.SIMPLE)
.compileReferencingRoot()
}
}
Result:
Note
There doesn't seem to be any literal values support, so this would be tricky to fix.
Note: This issue is about the
kotlinx.serialization
generator.Description
Given the code:
There is a difference between serializing
one
asParent
or asChildOne
:Json.encodeToString(one)
→{ "text": "some_text" }
Json.encodeToString<Parent>(one)
→{ "type": "package.name.ChildOne", "text": "some_text" }
The field name (here the default -
type
) can be changed by annotating the parent class with@JsonClassDiscriminator
, and the values by annotating the child classes with@SerialName
:Then:
Json.encodeToString<Parent>(one)
→{ "the_type": "child_one", "text": "some_text" }
Issue
The generated schemas do not currently contain the type discriminator field.
Example
Given the data types:
And the following config (schemas displayed using swagger-ui):
Result:
Note
There doesn't seem to be any literal values support, so this would be tricky to fix.