summaryrefslogtreecommitdiff
path: root/jvm
diff options
context:
space:
mode:
authorJakob Odersky <jakob@odersky.com>2018-03-07 14:07:25 -0800
committerJakob Odersky <jakob@odersky.com>2019-06-10 23:22:15 +0200
commita43a10a12fd5653e6050c652024764416b71ab54 (patch)
tree19824c4e4eb31f849d51520d57a484e4f4ca0640 /jvm
parentda8ed26cfed5e958eeb29a3444ff882a46090459 (diff)
downloadspray-json-a43a10a12fd5653e6050c652024764416b71ab54.tar.gz
spray-json-a43a10a12fd5653e6050c652024764416b71ab54.tar.bz2
spray-json-a43a10a12fd5653e6050c652024764416b71ab54.zip
Add support for ScalaJS and Scala Native
Binary compatibility with previous versions is maintained.
Diffstat (limited to 'jvm')
-rw-r--r--jvm/src/main/boilerplate/spray/json/ProductFormatsInstances.scala.template45
-rw-r--r--jvm/src/main/scala/spray/json/ProductFormats.scala155
-rw-r--r--jvm/src/test/scala/spray/json/JsonParserSpecJvm.scala62
-rw-r--r--jvm/src/test/scala/spray/json/ProductFormatsSpec.scala209
-rw-r--r--jvm/src/test/scala/spray/json/ReadmeSpec.scala98
5 files changed, 569 insertions, 0 deletions
diff --git a/jvm/src/main/boilerplate/spray/json/ProductFormatsInstances.scala.template b/jvm/src/main/boilerplate/spray/json/ProductFormatsInstances.scala.template
new file mode 100644
index 0000000..fa0d875
--- /dev/null
+++ b/jvm/src/main/boilerplate/spray/json/ProductFormatsInstances.scala.template
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011,2012 Mathias Doenitz, Johannes Rudolph
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package spray.json
+
+import scala.reflect.{ classTag, ClassTag }
+
+trait ProductFormatsInstances { self: ProductFormats with StandardFormats =>
+[# // Case classes with 1 parameters
+
+ def jsonFormat1[[#P1 :JF#], T <: Product :ClassTag](construct: ([#P1#]) => T): RootJsonFormat[T] = {
+ val Array([#p1#]) = extractFieldNames(classTag[T])
+ jsonFormat(construct, [#p1#])
+ }
+ def jsonFormat[[#P1 :JF#], T <: Product](construct: ([#P1#]) => T, [#fieldName1: String#]): RootJsonFormat[T] = new RootJsonFormat[T]{
+ def write(p: T) = {
+ val fields = new collection.mutable.ListBuffer[(String, JsValue)]
+ fields.sizeHint(1 * 2)
+ [#fields ++= productElement##2Field[P1](fieldName1, p, 0)#
+ ]
+ JsObject(fields.toSeq: _*)
+ }
+ def read(value: JsValue) = {
+ [#val p1V = fromField[P1](value, fieldName1)#
+ ]
+ construct([#p1V#])
+ }
+ }#
+
+
+]
+}
diff --git a/jvm/src/main/scala/spray/json/ProductFormats.scala b/jvm/src/main/scala/spray/json/ProductFormats.scala
new file mode 100644
index 0000000..81a48af
--- /dev/null
+++ b/jvm/src/main/scala/spray/json/ProductFormats.scala
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2011 Mathias Doenitz
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package spray.json
+
+import java.lang.reflect.Modifier
+import scala.annotation.tailrec
+import scala.util.control.NonFatal
+import scala.reflect.ClassTag
+
+/**
+ * Provides the helpers for constructing custom JsonFormat implementations for types implementing the Product trait
+ * (especially case classes)
+ */
+trait ProductFormats extends ProductFormatsInstances {
+ this: StandardFormats =>
+
+ def jsonFormat0[T](construct: () => T): RootJsonFormat[T] =
+ new RootJsonFormat[T] {
+ def write(p: T) = JsObject()
+ def read(value: JsValue) = value match {
+ case JsObject(_) => construct()
+ case _ => throw new DeserializationException("Object expected")
+ }
+ }
+
+ // helpers
+
+ protected def productElement2Field[T](fieldName: String, p: Product, ix: Int, rest: List[JsField] = Nil)
+ (implicit writer: JsonWriter[T]): List[JsField] = {
+ val value = p.productElement(ix).asInstanceOf[T]
+ writer match {
+ case _: OptionFormat[_] if (value == None) => rest
+ case _ => (fieldName, writer.write(value)) :: rest
+ }
+ }
+
+ protected def fromField[T](value: JsValue, fieldName: String)
+ (implicit reader: JsonReader[T]) = value match {
+ case x: JsObject if
+ (reader.isInstanceOf[OptionFormat[_]] &
+ !x.fields.contains(fieldName)) =>
+ None.asInstanceOf[T]
+ case x: JsObject =>
+ try reader.read(x.fields(fieldName))
+ catch {
+ case e: NoSuchElementException =>
+ deserializationError("Object is missing required member '" + fieldName + "'", e, fieldName :: Nil)
+ case DeserializationException(msg, cause, fieldNames) =>
+ deserializationError(msg, cause, fieldName :: fieldNames)
+ }
+ case _ => deserializationError("Object expected in field '" + fieldName + "'", fieldNames = fieldName :: Nil)
+ }
+
+ protected def extractFieldNames(tag: ClassTag[_]): Array[String] = {
+ val clazz = tag.runtimeClass
+ try {
+ // copy methods have the form copy$default$N(), we need to sort them in order, but must account for the fact
+ // that lexical sorting of ...8(), ...9(), ...10() is not correct, so we extract N and sort by N.toInt
+ val copyDefaultMethods = clazz.getMethods.filter(_.getName.startsWith("copy$default$")).sortBy(
+ _.getName.drop("copy$default$".length).takeWhile(_ != '(').toInt)
+ val fields = clazz.getDeclaredFields.filterNot { f =>
+ import Modifier._
+ (f.getModifiers & (TRANSIENT | STATIC | 0x1000 /* SYNTHETIC*/)) > 0
+ }
+ if (copyDefaultMethods.length != fields.length)
+ sys.error("Case class " + clazz.getName + " declares additional fields")
+ if (fields.zip(copyDefaultMethods).exists { case (f, m) => f.getType != m.getReturnType })
+ sys.error("Cannot determine field order of case class " + clazz.getName)
+ fields.map(f => ProductFormats.unmangle(f.getName))
+ } catch {
+ case NonFatal(ex) => throw new RuntimeException("Cannot automatically determine case class field names and order " +
+ "for '" + clazz.getName + "', please use the 'jsonFormat' overload with explicit field name specification", ex)
+ }
+ }
+
+}
+
+object ProductFormats {
+
+ private def unmangle(name: String) = {
+ import java.lang.{StringBuilder => JStringBuilder}
+ @tailrec def rec(ix: Int, builder: JStringBuilder): String = {
+ val rem = name.length - ix
+ if (rem > 0) {
+ var ch = name.charAt(ix)
+ var ni = ix + 1
+ val sb = if (ch == '$' && rem > 1) {
+ def c(offset: Int, ch: Char) = name.charAt(ix + offset) == ch
+ ni = name.charAt(ix + 1) match {
+ case 'a' if rem > 3 && c(2, 'm') && c(3, 'p') => { ch = '&'; ix + 4 }
+ case 'a' if rem > 2 && c(2, 't') => { ch = '@'; ix + 3 }
+ case 'b' if rem > 4 && c(2, 'a') && c(3, 'n') && c(4, 'g') => { ch = '!'; ix + 5 }
+ case 'b' if rem > 3 && c(2, 'a') && c(3, 'r') => { ch = '|'; ix + 4 }
+ case 'd' if rem > 3 && c(2, 'i') && c(3, 'v') => { ch = '/'; ix + 4 }
+ case 'e' if rem > 2 && c(2, 'q') => { ch = '='; ix + 3 }
+ case 'g' if rem > 7 && c(2, 'r') && c(3, 'e') && c(4, 'a') && c(5, 't') && c(6, 'e') && c(7, 'r') => { ch = '>'; ix + 8 }
+ case 'h' if rem > 4 && c(2, 'a') && c(3, 's') && c(4, 'h') => { ch = '#'; ix + 5 }
+ case 'l' if rem > 4 && c(2, 'e') && c(3, 's') && c(4, 's') => { ch = '<'; ix + 5 }
+ case 'm' if rem > 5 && c(2, 'i') && c(3, 'n') && c(4, 'u') && c(5, 's') => { ch = '-'; ix + 6 }
+ case 'p' if rem > 7 && c(2, 'e') && c(3, 'r') && c(4, 'c') && c(5, 'e') && c(6, 'n') && c(7, 't') => { ch = '%'; ix + 8 }
+ case 'p' if rem > 4 && c(2, 'l') && c(3, 'u') && c(4, 's') => { ch = '+'; ix + 5 }
+ case 'q' if rem > 5 && c(2, 'm') && c(3, 'a') && c(4, 'r') && c(5, 'k') => { ch = '?'; ix + 6 }
+ case 't' if rem > 5 && c(2, 'i') && c(3, 'l') && c(4, 'd') && c(5, 'e') => { ch = '~'; ix + 6 }
+ case 't' if rem > 5 && c(2, 'i') && c(3, 'm') && c(4, 'e') && c(5, 's') => { ch = '*'; ix + 6 }
+ case 'u' if rem > 2 && c(2, 'p') => { ch = '^'; ix + 3 }
+ case 'u' if rem > 5 =>
+ def hexValue(offset: Int): Int = {
+ val c = name.charAt(ix + offset)
+ if ('0' <= c && c <= '9') c - '0'
+ else if ('a' <= c && c <= 'f') c - 87
+ else if ('A' <= c && c <= 'F') c - 55 else -0xFFFF
+ }
+ val ci = (hexValue(2) << 12) + (hexValue(3) << 8) + (hexValue(4) << 4) + hexValue(5)
+ if (ci >= 0) { ch = ci.toChar; ix + 6 } else ni
+ case _ => ni
+ }
+ if (ni > ix + 1 && builder == null) new JStringBuilder(name.substring(0, ix)) else builder
+ } else builder
+ rec(ni, if (sb != null) sb.append(ch) else null)
+ } else if (builder != null) builder.toString else name
+ }
+ rec(0, null)
+ }
+}
+
+/**
+ * This trait supplies an alternative rendering mode for optional case class members.
+ * Normally optional members that are undefined (`None`) are not rendered at all.
+ * By mixing in this trait into your custom JsonProtocol you can enforce the rendering of undefined members as `null`.
+ * (Note that this only affect JSON writing, spray-json will always read missing optional members as well as `null`
+ * optional members as `None`.)
+ */
+trait NullOptions extends ProductFormats {
+ this: StandardFormats =>
+
+ override protected def productElement2Field[T](fieldName: String, p: Product, ix: Int, rest: List[JsField])
+ (implicit writer: JsonWriter[T]) = {
+ val value = p.productElement(ix).asInstanceOf[T]
+ (fieldName, writer.write(value)) :: rest
+ }
+}
diff --git a/jvm/src/test/scala/spray/json/JsonParserSpecJvm.scala b/jvm/src/test/scala/spray/json/JsonParserSpecJvm.scala
new file mode 100644
index 0000000..c0345e1
--- /dev/null
+++ b/jvm/src/test/scala/spray/json/JsonParserSpecJvm.scala
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2011 Mathias Doenitz
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package spray.json
+
+import org.specs2.mutable._
+import scala.util.control.NonFatal
+
+class JsonParserSpecJvm extends Specification {
+
+ "The JsonParser (on the JVM)" should {
+ "be reentrant" in {
+ import scala.concurrent.{Await, Future}
+ import scala.concurrent.duration._
+ import scala.concurrent.ExecutionContext.Implicits.global
+
+ val largeJsonSource = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/test.json")).mkString
+ val list = Await.result(
+ Future.traverse(List.fill(20)(largeJsonSource))(src => Future(JsonParser(src))),
+ 5.seconds
+ )
+ list.map(_.asInstanceOf[JsObject].fields("questions").asInstanceOf[JsArray].elements.size) === List.fill(20)(100)
+ }
+ "fail gracefully for deeply nested structures" in {
+ val queue = new java.util.ArrayDeque[String]()
+
+ // testing revealed that each recursion will need approx. 280 bytes of stack space
+ val depth = 1500
+ val runnable = new Runnable {
+ override def run(): Unit =
+ try {
+ val nested = "[{\"key\":" * (depth / 2)
+ JsonParser(nested)
+ queue.push("didn't fail")
+ } catch {
+ case s: StackOverflowError => queue.push("stackoverflow")
+ case NonFatal(e) =>
+ queue.push(s"nonfatal: ${e.getMessage}")
+ }
+ }
+
+ val thread = new Thread(null, runnable, "parser-test", 655360)
+ thread.start()
+ thread.join()
+ queue.peek() === "nonfatal: JSON input nested too deeply:JSON input was nested more deeply than the configured limit of maxNesting = 1000"
+ }
+ }
+
+}
diff --git a/jvm/src/test/scala/spray/json/ProductFormatsSpec.scala b/jvm/src/test/scala/spray/json/ProductFormatsSpec.scala
new file mode 100644
index 0000000..f42c46d
--- /dev/null
+++ b/jvm/src/test/scala/spray/json/ProductFormatsSpec.scala
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2011 Mathias Doenitz
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package spray.json
+
+import org.specs2.mutable._
+
+class ProductFormatsSpec extends Specification {
+
+ case class Test0()
+ case class Test2(a: Int, b: Option[Double])
+ case class Test3[A, B](as: List[A], bs: List[B])
+ case class Test4(t2: Test2)
+ case class TestTransient(a: Int, b: Option[Double]) {
+ @transient var c = false
+ }
+ @SerialVersionUID(1L) // SerialVersionUID adds a static field to the case class
+ case class TestStatic(a: Int, b: Option[Double])
+ case class TestMangled(`foo-bar!`: Int, `User ID`: String, `ü$bavf$u56ú$`: Boolean, `-x-`: Int, `=><+-*/!@#%^&~?|`: Float)
+
+ trait TestProtocol {
+ this: DefaultJsonProtocol =>
+ implicit val test0Format = jsonFormat0(Test0)
+ implicit val test2Format = jsonFormat2(Test2)
+ implicit def test3Format[A: JsonFormat, B: JsonFormat] = jsonFormat2(Test3.apply[A, B])
+ implicit def test4Format = jsonFormat1(Test4)
+ implicit def testTransientFormat = jsonFormat2(TestTransient)
+ implicit def testStaticFormat = jsonFormat2(TestStatic)
+ implicit def testMangledFormat = jsonFormat5(TestMangled)
+ }
+ object TestProtocol1 extends DefaultJsonProtocol with TestProtocol
+ object TestProtocol2 extends DefaultJsonProtocol with TestProtocol with NullOptions
+
+ "A JsonFormat created with `jsonFormat`, for a case class with 2 elements," should {
+ import TestProtocol1._
+ val obj = Test2(42, Some(4.2))
+ val json = JsObject("a" -> JsNumber(42), "b" -> JsNumber(4.2))
+ "convert to a respective JsObject" in {
+ obj.toJson mustEqual json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[Test2] mustEqual obj
+ }
+ "throw a DeserializationException if the JsObject does not all required members" in (
+ JsObject("b" -> JsNumber(4.2)).convertTo[Test2] must
+ throwA(new DeserializationException("Object is missing required member 'a'"))
+ )
+ "not require the presence of optional fields for deserialization" in {
+ JsObject("a" -> JsNumber(42)).convertTo[Test2] mustEqual Test2(42, None)
+ }
+ "not render `None` members during serialization" in {
+ Test2(42, None).toJson mustEqual JsObject("a" -> JsNumber(42))
+ }
+ "ignore additional members during deserialization" in {
+ JsObject("a" -> JsNumber(42), "b" -> JsNumber(4.2), "c" -> JsString(Symbol("no"))).convertTo[Test2] mustEqual obj
+ }
+ "not depend on any specific member order for deserialization" in {
+ JsObject("b" -> JsNumber(4.2), "a" -> JsNumber(42)).convertTo[Test2] mustEqual obj
+ }
+ "throw a DeserializationException if the JsValue is not a JsObject" in (
+ JsNull.convertTo[Test2] must throwA(new DeserializationException("Object expected in field 'a'"))
+ )
+ "expose the fieldName in the DeserializationException when able" in {
+ JsNull.convertTo[Test2] must throwA[DeserializationException].like {
+ case DeserializationException(_, _, fieldNames) => fieldNames mustEqual "a" :: Nil
+ }
+ }
+ "expose all gathered fieldNames in the DeserializationException" in {
+ JsObject("t2" -> JsObject("a" -> JsString("foo"))).convertTo[Test4] must throwA[DeserializationException].like {
+ case DeserializationException(_, _, fieldNames) => fieldNames mustEqual "t2" :: "a" :: Nil
+ }
+ }
+ }
+
+ "A JsonProtocol mixing in NullOptions" should {
+ "render `None` members to `null`" in {
+ import TestProtocol2._
+ Test2(42, None).toJson mustEqual JsObject("a" -> JsNumber(42), "b" -> JsNull)
+ }
+ }
+
+ "A JsonFormat for a generic case class and created with `jsonFormat`" should {
+ import TestProtocol1._
+ val obj = Test3(42 :: 43 :: Nil, "x" :: "y" :: "z" :: Nil)
+ val json = JsObject(
+ "as" -> JsArray(JsNumber(42), JsNumber(43)),
+ "bs" -> JsArray(JsString("x"), JsString("y"), JsString("z"))
+ )
+ "convert to a respective JsObject" in {
+ obj.toJson mustEqual json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[Test3[Int, String]] mustEqual obj
+ }
+ }
+ "A JsonFormat for a case class with 18 parameters and created with `jsonFormat`" should {
+ object Test18Protocol extends DefaultJsonProtocol {
+ implicit val test18Format = jsonFormat18(Test18)
+ }
+ case class Test18(
+ a1: String,
+ a2: String,
+ a3: String,
+ a4: String,
+ a5: Int,
+ a6: String,
+ a7: String,
+ a8: String,
+ a9: String,
+ a10: String,
+ a11: String,
+ a12: Double,
+ a13: String,
+ a14: String,
+ a15: String,
+ a16: String,
+ a17: String,
+ a18: String)
+
+ import Test18Protocol._
+ val obj = Test18("a1", "a2", "a3", "a4", 5, "a6", "a7", "a8", "a9",
+ "a10", "a11", 12d, "a13", "a14", "a15", "a16", "a17", "a18")
+
+ val json = JsonParser("""{"a1":"a1","a2":"a2","a3":"a3","a4":"a4","a5":5,"a6":"a6","a7":"a7","a8":"a8","a9":"a9","a10":"a10","a11":"a11","a12":12.0,"a13":"a13","a14":"a14","a15":"a15","a16":"a16","a17":"a17","a18":"a18"}""")
+ "convert to a respective JsObject" in {
+ obj.toJson mustEqual json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[Test18] mustEqual obj
+ }
+ }
+
+ "A JsonFormat for a generic case class with an explicitly provided type parameter" should {
+ "support the jsonFormat1 syntax" in {
+ case class Box[A](a: A)
+ object BoxProtocol extends DefaultJsonProtocol {
+ implicit val boxFormat = jsonFormat1(Box[Int])
+ }
+ import BoxProtocol._
+ Box(42).toJson === JsObject(Map("a" -> JsNumber(42)))
+ }
+ }
+
+ "A JsonFormat for a case class with transient fields and created with `jsonFormat`" should {
+ import TestProtocol1._
+ val obj = TestTransient(42, Some(4.2))
+ val json = JsObject("a" -> JsNumber(42), "b" -> JsNumber(4.2))
+ "convert to a respective JsObject" in {
+ obj.toJson mustEqual json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[TestTransient] mustEqual obj
+ }
+ }
+
+ "A JsonFormat for a case class with static fields and created with `jsonFormat`" should {
+ import TestProtocol1._
+ val obj = TestStatic(42, Some(4.2))
+ val json = JsObject("a" -> JsNumber(42), "b" -> JsNumber(4.2))
+ "convert to a respective JsObject" in {
+ obj.toJson mustEqual json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[TestStatic] mustEqual obj
+ }
+ }
+
+ "A JsonFormat created with `jsonFormat`, for a case class with 0 elements," should {
+ import TestProtocol1._
+ val obj = Test0()
+ val json = JsObject()
+ "convert to a respective JsObject" in {
+ obj.toJson mustEqual json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[Test0] mustEqual obj
+ }
+ "ignore additional members during deserialization" in {
+ JsObject("a" -> JsNumber(42)).convertTo[Test0] mustEqual obj
+ }
+ "throw a DeserializationException if the JsValue is not a JsObject" in (
+ JsNull.convertTo[Test0] must throwA(new DeserializationException("Object expected"))
+ )
+ }
+
+ "A JsonFormat created with `jsonFormat`, for a case class with mangled-name members," should {
+ import TestProtocol1._
+ val json = """{"ü$bavf$u56ú$":true,"=><+-*/!@#%^&~?|":1.0,"foo-bar!":42,"-x-":26,"User ID":"Karl"}""".parseJson
+ "produce the correct JSON" in {
+ TestMangled(42, "Karl", true, 26, 1.0f).toJson === json
+ }
+ "convert a JsObject to the respective case class instance" in {
+ json.convertTo[TestMangled] === TestMangled(42, "Karl", true, 26, 1.0f)
+ }
+ }
+}
diff --git a/jvm/src/test/scala/spray/json/ReadmeSpec.scala b/jvm/src/test/scala/spray/json/ReadmeSpec.scala
new file mode 100644
index 0000000..306b656
--- /dev/null
+++ b/jvm/src/test/scala/spray/json/ReadmeSpec.scala
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2011 Mathias Doenitz
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package spray.json
+
+import org.specs2.mutable._
+
+class ReadmeSpec extends Specification {
+
+ "The Usage snippets" should {
+ "behave as expected" in {
+ import DefaultJsonProtocol._
+
+ val source = """{ "some": "JSON source" }"""
+ val jsonAst = source.parseJson
+ jsonAst mustEqual JsObject("some" -> JsString("JSON source"))
+
+ val json2 = jsonAst.prettyPrint
+ json2 mustEqual
+ """{
+ | "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 = jsonFormat4(Color)
+ }
+ import MyJsonProtocol._
+ color.toJson.convertTo[Color] mustEqual color
+ }
+ }
+
+ "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) =
+ JsArray(JsString(c.name), JsNumber(c.red), JsNumber(c.green), JsNumber(c.blue))
+
+ def read(value: JsValue) = value match {
+ 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._
+ 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
+ }
+ }
+
+} \ No newline at end of file