Created
March 25, 2011 15:48
-
-
Save debasishg/887058 to your computer and use it in GitHub Desktop.
Serialization of Double.NaN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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