From 8e6d79cfc3080c276890a2653c545dade6387cf8 Mon Sep 17 00:00:00 2001 From: Mathias Date: Wed, 1 Feb 2012 10:56:57 +0100 Subject: Improve ReadmeSpec --- src/test/scala/cc/spray/json/ReadmeSpec.scala | 58 +++++++++++++++++---------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/src/test/scala/cc/spray/json/ReadmeSpec.scala b/src/test/scala/cc/spray/json/ReadmeSpec.scala index d60aa69..e67312d 100644 --- a/src/test/scala/cc/spray/json/ReadmeSpec.scala +++ b/src/test/scala/cc/spray/json/ReadmeSpec.scala @@ -33,49 +33,65 @@ class ReadmeSpec extends Specification { """{ | "some": "JSON source" |}""".stripMargin - + val jsonAst2 = List(1, 2, 3).toJson jsonAst2 mustEqual JsArray(JsNumber(1), JsNumber(2), JsNumber(3)) } } - + case class Color(name: String, red: Int, green: Int, blue: Int) - + val color = Color("CadetBlue", 95, 158, 160) + "The case class example" should { "behave as expected" in { object MyJsonProtocol extends DefaultJsonProtocol { implicit val colorFormat = jsonFormat(Color, "name", "red", "green", "blue") - } + } import MyJsonProtocol._ - - val json = Color("CadetBlue", 95, 158, 160).toJson - val color = json.convertTo[Color] - - color mustEqual Color("CadetBlue", 95, 158, 160) + color.toJson.convertTo[Color] mustEqual color } } - - "The non case class example" should { + + "The non case class (array) example" should { "behave as expected" in { object MyJsonProtocol extends DefaultJsonProtocol { implicit object ColorJsonFormat extends JsonFormat[Color] { - def write(c: Color) = { + def write(c: Color) = JsArray(JsString(c.name), JsNumber(c.red), JsNumber(c.green), JsNumber(c.blue)) - } + def read(value: JsValue) = value match { - case JsArray(JsString(name) :: JsNumber(red) :: JsNumber(green) :: JsNumber(blue) :: Nil) => { + case JsArray(Seq(JsString(name), JsNumber(red), JsNumber(green), JsNumber(blue))) => new Color(name, red.toInt, green.toInt, blue.toInt) - } case _ => deserializationError("Color expected") } } - } + } import MyJsonProtocol._ - - val json = Color("CadetBlue", 95, 158, 160).toJson - val color = json.convertTo[Color] - - color mustEqual Color("CadetBlue", 95, 158, 160) + color.toJson.convertTo[Color] mustEqual color + } + } + + "The non case class (object) example" should { + "behave as expected" in { + object MyJsonProtocol extends DefaultJsonProtocol { + implicit object ColorJsonFormat extends JsonFormat[Color] { + def write(c: Color) = JsObject( + "name" -> JsString(c.name), + "red" -> JsNumber(c.red), + "green" -> JsNumber(c.green), + "blue" -> JsNumber(c.blue) + ) + def read(value: JsValue) = { + value.asJsObject.getFields("name", "red", "green", "blue") match { + case Seq(JsString(name), JsNumber(red), JsNumber(green), JsNumber(blue)) => + new Color(name, red.toInt, green.toInt, blue.toInt) + case _ => throw new DeserializationException("Color expected") + } + } + } + } + import MyJsonProtocol._ + color.toJson.convertTo[Color] mustEqual color } } -- cgit v1.2.3