When using Json.toJson with Float.Nan or Double.Nan a NumberFormatException is thrown.
Play version 2.1.3, Java 7 on Osx
NumberFormatException: null (BigDecimal.java:470)
[error] play.api.libs.json.DefaultWrites$DoubleWrites$.writes(Writes.scala:124)
[error] play.api.libs.json.DefaultWrites$DoubleWrites$.writes(Writes.scala:123)
[error] play.api.libs.json.Json$.toJson(Json.scala:83)
[error] JsonNanBug$$anonfun$4$$anonfun$apply$10$$anonfun$apply$11.apply(JsonNanBug.scala:32)
[error] JsonNanBug$$anonfun$4$$anonfun$apply$10$$anonfun$apply$11.apply(JsonNanBug.scala:32)
[error] JsonNanBug$$anonfun$4$$anonfun$apply$10.apply(JsonNanBug.scala:32)
[error] JsonNanBug$$anonfun$4$$anonfun$apply$10.apply(JsonNanBug.scala:32)
Below is a simple specs2 test to prove the point.
(I'll attach the file as well if that's possible, but it's not from this git hub screen)
import org.specs2.mutable.Specification
import play.api.libs.json.Json
/**
"JSON converter" should {
"cope with ordinary float" in {
Json.toJson(42.0f) must not beNull
}
}
"JSON converter" should {
"cope with Float.Nan" in {
Json.toJson(Float.NaN) must not beNull
}
}
"JSON converter" should {
"cope with ordinary double" in {
Json.toJson(3.141d) must not beNull
}
}
"JSON converter" should {
"cope with Double.Nan" in {
Json.toJson(Double.NaN) must not beNull
}
}
}
What do you think the correct behavior is? Since NaN isn't directly representable in JSON, you'd have to write a null or some other marker value in its place.
Since NaN or infinity cannot be represented in JSON I would say exception makes sense here. If you want to override the default behavior you can always pass in another Writer
Wow, my bad.
I had assumed that since javascript has an isNaN() function (so obviously supports NaN) that JSON would also support NaN.
I've learnt something today.
Most helpful comment
Wow, my bad.
I had assumed that since javascript has an isNaN() function (so obviously supports NaN) that JSON would also support NaN.
I've learnt something today.