Skip to content

Conversation

@daniCsorbaJB
Copy link

@daniCsorbaJB daniCsorbaJB commented Oct 30, 2025

This is the fifth part of the Kotlin Serialization rewrite task.

Related Youtrack ticket: KT-81979


* Serialize Kotlin objects to JSON strings using the [`encodeToString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/encode-to-string.html) function.
* Deserialize JSON strings back to Kotlin objects with the [`decodeFromString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/decode-from-string.html) function.
* Work directly with the [`JsonElement`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-element/) when handling complex JSON structures using the [`encodeToJsonElement()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/encode-to-json-element.html) and the [`decodeFromJsonElement()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/decode-from-json-element.html) functions.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see we can nicely add encodeToStream/decodeFromStream to the list here. IMO it's OK to add a separate page for them + Okio integration

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes it definitely fits neatly here 👍


* Serialize Kotlin objects to JSON strings using the [`encodeToString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/encode-to-string.html) function.
* Deserialize JSON strings back to Kotlin objects with the [`decodeFromString()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/decode-from-string.html) function.
* Work directly with the [`JsonElement`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-element/) when handling complex JSON structures using the [`encodeToJsonElement()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/encode-to-json-element.html) and the [`decodeFromJsonElement()`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/decode-from-json-element.html) functions.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we give the link to serialization-json-elements.md here instead of API reference for JsonElement? IMO guides are easier to read than plain reference.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure thing 👍 good idea — we can modify it as:


### Encode default values

By default, the JSON serializer doesn't encode default property values because they are automatically applied to missing properties during decoding.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
By default, the JSON serializer doesn't encode default property values because they are automatically applied to missing properties during decoding.
By default, the JSON format doesn't encode default property values because they are automatically applied to missing properties during decoding.

(to avoid confusion with KSerializer instances, to which we usualy refer as serializers)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 fair point
My concern with using “JSON format” is that I think it might sound like the JSON spec itself defines rules about default values, which it doesn’t. (or I couldn't find anything in the spec)

What do you think about shifting it to the encoder as the "actor" here? or would that be still confusing 🤔 :

By default, the JSON encoder omits default property values because they are automatically applied to missing properties during decoding.

```
{kotlin-runnable="true"}

> [`@JsonClassDiscriminator`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-class-discriminator/) is [Experimental](components-stability.md#stability-levels-explained). To opt in, use the `@OptIn(ExperimentalSerializationApi::class)` annotation or the compiler option `-opt-in=kotlinx.serialization.ExperimentalSerializationApi`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Experimentality warning about JsonClassDiscriminator before introducing JsonClassDiscriminator itself is strange. This block should be moved one paragraph down.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was a way to avoid having too many notes next to each other, but I think we could just remove this and instead add it like:

While the classDiscriminator property in a Json instance lets you specify a single discriminator key for all polymorphic types, the Experimental @JsonClassDiscriminator annotation offers more flexibility.


fun main() {
// Decodes a JSON string with lenient parsing
// Lenient parsing allows unquoted keys, string and enum values, and quoted integers
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Lenient parsing allows unquoted keys, string and enum values, and quoted integers
// Lenient parsing allows unquoted keys, string and enum values.

(we allow quoted integers without this flag too)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We even have Note that parsing of quoted numbers or booleans such as votes: "9000" to val votes: Int is generally allowed by kotlinx.serialization regardless of the isLenient flag, since such JSON is syntactically valid. note below

>
{style="note"}

## Customize JSON deserialization
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a pair of new flags that aren't in docs yet: allowTrailingComma and allowComments. Can you take care of them, please? (they won't be experimental in next release)

Copy link
Author

@daniCsorbaJB daniCsorbaJB Nov 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing 👍

What do you think about placing it under Lenient parsing (it won't appear in the navigation, but if someone is looking for leniency, I'm pretty sure they would look for it there and will find it)

Something like:

Allow trailing commas

To allow trailing commas in JSON input, set the allowTrailingComma property to true:

// Imports declarations from the serialization library
import kotlinx.serialization.*
import kotlinx.serialization.json.*

//sampleStart
// Allows trailing commas in JSON objects and arrays
val format = Json { allowTrailingComma = true }

fun main() {
    val numbers = format.decodeFromString<List<Int>>(
        """
            [1, 2, 3,]
        """
    )
    println(numbers)
    // [1, 2, 3]
}
//sampleEnd

{kotlin-runnable="true"}

Allow comments in JSON

Use the allowComments property to allow comments in JSON input.
When this property is enabled, the parser accepts the following comment forms in the input:

  • // line comments that end at a newline \n
  • /* */ block comments

Nested block comments aren't supported

{style="note"}

Here's an example:

// Imports declarations from the serialization library
import kotlinx.serialization.*
import kotlinx.serialization.json.*

//sampleStart
// Allows comments in JSON input
val format = Json { allowComments = true }

fun main() {
    val numbers = format.decodeFromString<List<Int>>(
        """
            [
                // first element
                1,
                /* second element */
                2
            ]
        """
    )
    println(numbers)
    // [1, 2]
}
//sampleEnd

{kotlin-runnable="true"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants