Skip to content

Json.decodeFromString with data class serializers tolerates missing commas in encoded data #2287

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
gmkohler opened this issue Apr 28, 2023 · 0 comments
Assignees

Comments

@gmkohler
Copy link

gmkohler commented Apr 28, 2023

Describe the bug

@Serializable serializers are successfully decoding JSON that is missing commas between its properties

To Reproduce

These tests will pass with multiple properties and multiple combinations of missing commas, so not a special case of N = 2.

import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.api.expectThrows
import strikt.assertions.contains
import strikt.assertions.isEqualTo
import strikt.assertions.isNotNull


class JsonTest {
    @Serializable
    data class Foo(
        val bar: String,
        val baz: Int,
    )

    val invalidEncoding = """{
        "bar": "buz"
        "baz": 1
    }""".trimIndent()

    @Test
    fun `decoding invalid JSON is tolerated by @Serializable serializers`() {
        val result = Json.decodeFromString(Foo.serializer(), invalidEncoding)

        expectThat(result) {
            get(Foo::bar) isEqualTo "buz"
            get(Foo::baz) isEqualTo 1
        }
    }

    @Test
    fun `decoding invalid JSON is not tolerated by JsonObject's serializer`() {
        expectThrows<SerializationException> {
            Json.decodeFromString(JsonObject.serializer(), invalidEncoding)
        }.and {
            get(SerializationException::message).isNotNull().contains("Unexpected JSON token")
        }
    }
}

Expected behavior

The decoding invalid JSON is tolerated by @Serializable serializers test should fail decoding the invalid JSON

Environment

  • Kotlin version: 1.8.20
  • Library version: 1.4.1
  • Kotlin platforms: JVM
  • Gradle version: 7.5
  • IDE version (if bug is related to the IDE) IntelliJ 2023.1 CE
  • Other relevant context JDK 17
@gmkohler gmkohler changed the title decodeFromString with data class serializers tolerates missing commas in JSON Json.decodeFromString with data class serializers tolerates missing commas in encoded data Apr 28, 2023
alisa101rs added a commit to alisa101rs/kotlinx.serialization that referenced this issue Dec 17, 2024
@sandwwraith sandwwraith self-assigned this Jan 6, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

2 participants