Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created March 25, 2011 15:48
Show Gist options
  • Save debasishg/887058 to your computer and use it in GitHub Desktop.
Save debasishg/887058 to your computer and use it in GitHub Desktop.
Serialization of Double.NaN
// sample class with a double value
case class DoubleNanTest(price: Double)
// define typeclass instance for serialization
import dispatch.json._
implicit val DoubleNanTestFormat: Format[DoubleNanTest] = new Format[DoubleNanTest] {
def reads(json: JsValue): DoubleNanTest = json match {
case JsString("Double.NaN") => DoubleNanTest(scala.Double.NaN) // special treatment for NaN
case JsNumber(n) => DoubleNanTest(n.doubleValue)
case _ => error("Invalid DoubleNanTest")
}
def writes(a: DoubleNanTest): JsValue = a.price match {
case x if x equals scala.Double.NaN => JsString("Double.NaN") // special treatment for NaN
case x => JsNumber(BigDecimal.valueOf(x))
}
}
// test script for serialization
describe("Serialization of double NaN") {
it ("should serialize") {
val x = DoubleNanTest(scala.Double.NaN)
x.price.isNaN should equal(true)
fromjson[DoubleNanTest](tojson(x)).price.isNaN should equal(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment