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

`coerceInputValues` does not work for `Double` type when value is `NaN`.

Open BoxResin opened this issue 1 year ago • 2 comments

Describe the bug coerceInputValues does not work for Double type when value is NaN.

To Reproduce

@Serializable
data class MyData(
    val doubleField: Double = .0
)

...

val json = Json {
    coerceInputValues = true
}

val data: MyData = """
{
    "doubleField": NaN
}""".let { json.decodeFromString(it) }

println(data)

This prints:

kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 41: Unexpected special floating-point value NaN. By default, non-finite floating point values are prohibited because they do not conform JSON specification at path: $.doubleField It is possible to deserialize them using 'JsonBuilder.allowSpecialFloatingPointValues = true' JSON input: { "doubleField": NaN }

Expected behavior I don't want to set allowSpecialFloatingPointValues to true, but want it to be coerced to .0.

Any good ideas for a workaround?

Environment

  • Kotlin version: 1.8.20
  • Library version: 1.6.1
  • Kotlin platforms: JVM
  • Gradle version: 8.0

BoxResin avatar Feb 01 '24 03:02 BoxResin

That's an interesting request. Can you explain the situation in more detail, what kind of API do you use, and why do you need coercing?

The current workaround is to either write a custom serializer or make the property var and rewrite it in the init {} block.

sandwwraith avatar Feb 05 '24 18:02 sandwwraith

@sandwwraith

I mostly use kotlinx.serialization to parse JSON responses of web API. Sometimes, due to a server problem, a part of response is incorrect and it causes entire JSON parsing error. it would be nice if at least some functions of the client app could continue to work by coercing some invalid values into the default. (Imagine that the web API is for a dashboard page.)

Actually, the coerceInputValues option does it except of NaN. I want coerceInputValues to be effective too if the incorrect value is NaN.

Thank you for your reply.

BoxResin avatar Feb 14 '24 15:02 BoxResin