-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
fix(kotlin): support oneOf with primitive types in kotlinx_serialization #22986
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,22 +39,22 @@ import kotlinx.serialization.encoding.Encoder | |
| {{/enumUnknownDefaultCase}} | ||
| {{^enumUnknownDefaultCase}} | ||
| {{#generateOneOfAnyOfWrappers}} | ||
| {{#discriminator}} | ||
| import kotlinx.serialization.KSerializer | ||
| import kotlinx.serialization.encoding.Decoder | ||
| import kotlinx.serialization.encoding.Encoder | ||
| {{/discriminator}} | ||
| {{/generateOneOfAnyOfWrappers}} | ||
| {{/enumUnknownDefaultCase}} | ||
| {{#generateOneOfAnyOfWrappers}} | ||
| {{#discriminator}} | ||
| import kotlinx.serialization.SerializationException | ||
| import kotlinx.serialization.descriptors.SerialDescriptor | ||
| import kotlinx.serialization.descriptors.buildClassSerialDescriptor | ||
| import kotlinx.serialization.json.JsonDecoder | ||
| import kotlinx.serialization.json.JsonEncoder | ||
| import kotlinx.serialization.json.JsonObject | ||
| import kotlinx.serialization.json.JsonElement | ||
| import kotlinx.serialization.json.JsonNull | ||
| import kotlinx.serialization.json.JsonPrimitive | ||
| {{#discriminator}} | ||
| import kotlinx.serialization.json.JsonObject | ||
| import kotlinx.serialization.json.jsonObject | ||
| import kotlinx.serialization.json.jsonPrimitive | ||
| {{/discriminator}} | ||
|
|
@@ -100,13 +100,17 @@ import java.io.IOException | |
| {{#discriminator}} | ||
| @Serializable(with = {{classname}}Serializer::class) | ||
| {{/discriminator}} | ||
| {{^discriminator}} | ||
| {{#serializableModel}}@KSerializable(with = {{classname}}.{{classname}}Serializer::class){{/serializableModel}}{{^serializableModel}}@Serializable(with = {{classname}}.{{classname}}Serializer::class){{/serializableModel}} | ||
| {{/discriminator}} | ||
| {{/generateOneOfAnyOfWrappers}} | ||
| {{/kotlinx_serialization}} | ||
| {{#isDeprecated}} | ||
| @Deprecated(message = "This schema is deprecated.") | ||
| {{/isDeprecated}} | ||
| {{>additionalModelTypeAnnotations}} | ||
| {{#kotlinx_serialization}} | ||
| {{#discriminator}} | ||
| {{#nonPublicApi}}internal {{/nonPublicApi}}{{^nonPublicApi}}{{#explicitApi}}public {{/explicitApi}}{{/nonPublicApi}}sealed interface {{classname}} { | ||
| {{#discriminator.mappedModels}} | ||
| @JvmInline | ||
|
|
@@ -150,6 +154,78 @@ import java.io.IOException | |
| } | ||
| } | ||
| } | ||
| {{/discriminator}} | ||
| {{^discriminator}} | ||
| {{#nonPublicApi}}internal {{/nonPublicApi}}{{^nonPublicApi}}{{#explicitApi}}public {{/explicitApi}}{{/nonPublicApi}}data class {{classname}}(var actualInstance: Any? = null) { | ||
|
|
||
| {{#nonPublicApi}}internal {{/nonPublicApi}}{{^nonPublicApi}}{{#explicitApi}}public {{/explicitApi}}{{/nonPublicApi}}object {{classname}}Serializer : KSerializer<{{classname}}> { | ||
| override val descriptor: SerialDescriptor = buildClassSerialDescriptor("{{classname}}") { | ||
| element("type", JsonPrimitive.serializer().descriptor) | ||
| element("actualInstance", JsonElement.serializer().descriptor) | ||
| } | ||
|
|
||
| override fun serialize(encoder: Encoder, value: {{classname}}) { | ||
| val jsonEncoder = encoder as? JsonEncoder ?: throw SerializationException("{{classname}} can only be serialized with Json") | ||
|
|
||
| when (val instance = value.actualInstance) { | ||
| {{#composedSchemas}} | ||
| {{#oneOf}} | ||
| {{#isPrimitiveType}} | ||
| {{#isString}} | ||
| is kotlin.String -> jsonEncoder.encodeString(instance) | ||
| {{/isString}} | ||
| {{#isBoolean}} | ||
| is kotlin.Boolean -> jsonEncoder.encodeBoolean(instance) | ||
| {{/isBoolean}} | ||
| {{#isInteger}} | ||
| {{^isLong}} | ||
| is kotlin.Int -> jsonEncoder.encodeInt(instance) | ||
| {{/isLong}} | ||
| {{/isInteger}} | ||
| {{#isLong}} | ||
| is kotlin.Long -> jsonEncoder.encodeLong(instance) | ||
| {{/isLong}} | ||
| {{#isNumber}} | ||
| {{#isDouble}} | ||
| is kotlin.Double -> jsonEncoder.encodeDouble(instance) | ||
| {{/isDouble}} | ||
| {{#isFloat}} | ||
| is kotlin.Float -> jsonEncoder.encodeFloat(instance) | ||
| {{/isFloat}} | ||
| {{/isNumber}} | ||
| {{/isPrimitiveType}} | ||
| {{^isPrimitiveType}} | ||
| is {{{dataType}}} -> jsonEncoder.encodeSerializableValue({{{dataType}}}.serializer(), instance) | ||
| {{/isPrimitiveType}} | ||
| {{/oneOf}} | ||
| {{/composedSchemas}} | ||
| null -> jsonEncoder.encodeJsonElement(JsonNull) | ||
| else -> throw SerializationException("Unknown type in actualInstance: ${instance::class}") | ||
| } | ||
| } | ||
|
|
||
| override fun deserialize(decoder: Decoder): {{classname}} { | ||
| val jsonDecoder = decoder as? JsonDecoder ?: throw SerializationException("{{classname}} can only be deserialized with Json") | ||
| val jsonElement = jsonDecoder.decodeJsonElement() | ||
|
|
||
| val errorMessages = mutableListOf<String>() | ||
|
|
||
| {{#composedSchemas}} | ||
| {{#oneOf}} | ||
| try { | ||
| val instance = jsonDecoder.json.decodeFromJsonElement<{{{dataType}}}>(jsonElement) | ||
| return {{classname}}(actualInstance = instance) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: oneOf deserialization returns on the first successful decode without checking for multiple matches, so ambiguous primitives (e.g., Int/Long/Double) will silently select the first schema instead of enforcing exactly one match. Prompt for AI agents
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is consistent with the existing multiplatform template (libraries/multiplatform/oneof_class.mustache L64-72) which uses the same try-each approach.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Non-discriminator oneOf deserialization returns on the first successful decode, so overlapping primitive schemas can match multiple types but the first one wins, violating oneOf’s “exactly one” semantics. Prompt for AI agents
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same as the previous comment — this is the same try-each approach used in the multiplatform template ( oneOf semantics require the schemas to be mutually exclusive, so the first-match behavior is by design. |
||
| } catch (e: Exception) { | ||
| errorMessages.add("Failed to deserialize as {{{dataType}}}: ${e.message}") | ||
| } | ||
| {{/oneOf}} | ||
| {{/composedSchemas}} | ||
|
|
||
| throw SerializationException("Cannot deserialize {{classname}}. Tried: ${errorMessages.joinToString(", ")}") | ||
| } | ||
| } | ||
| } | ||
| {{/discriminator}} | ||
| {{/kotlinx_serialization}} | ||
| {{^kotlinx_serialization}} | ||
| {{#nonPublicApi}}internal {{/nonPublicApi}}{{^nonPublicApi}}{{#explicitApi}}public {{/explicitApi}}{{/nonPublicApi}}data class {{classname}}(var actualInstance: Any? = null) { | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2:
{{{dataType}}}.serializer()will not compile for parameterized/collection oneOf types (e.g.,List<Foo>/Map<String,Bar>), so the generated Kotlin for oneOf with array/map schemas will fail to compile. Use a collection serializer or the top‑levelserializer<T>()instead.Prompt for AI agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This line is ported directly from the existing multiplatform template (
libraries/multiplatform/oneof_class.mustacheL49), which uses the same pattern.This PR focuses on primitive type oneOf support.
Collection/parameterized type handling in oneOf is a broader issue that affects the multiplatform template as well and should be addressed separately.