Kotlin / kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Apache License 2.0
5.39k stars 620 forks source link

JsonPrimitive.intOrNull returns an invalid value instead of null when the content string starts with a digit #2656

Open codeZfox opened 5 months ago

codeZfox commented 5 months ago

Extension property JsonPrimitive.intOrNull returns an invalid value instead of null when the content string starts with a digit

To Reproduce

    @Serializable
    class SomeData(
        @SerialName("number")
        val number: Int
    )

   val someData2 = Json.decodeFromString<SomeData>("""{"number": "3 digit then random string"}""")

   someData2.number == 3 // true

the actual value in the number field is 3

Expected behavior the expected value in the number field is 3

Environment

sandwwraith commented 5 months ago

Hi, can you please clarify the issue? I do not see any usages of JsonPrimitive.intOrNull in your code. decodeFromString function tries to map input directly onto @Serializable class. If a value cannot be converted to Int, an exception is thrown. "3 digit then random string" cannot be converted to Int, because it is not appropriate to convert only a part of the string.