kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

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

Open codeZfox opened this issue 1 year ago • 1 comments

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

  • Kotlin version: 1.9.10
  • Library version: 1.6.0+
  • Kotlin platforms: JVM

codeZfox avatar Apr 29 '24 07:04 codeZfox

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.

sandwwraith avatar Apr 29 '24 10:04 sandwwraith