aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJakob Odersky <jakob@odersky.com>2018-02-14 12:17:15 -0800
committerJakob Odersky <jakob@odersky.com>2018-02-14 12:17:15 -0800
commiteada4c48b3954241e130f5d9b5e7feebe8c1e3f2 (patch)
treed017b30fb264b0560cbf7df3540f26e705da8ec0
parentaf6845cc08ae223ad67ebad61559d8264fd3346b (diff)
downloadspray-json-derivation-eada4c48b3954241e130f5d9b5e7feebe8c1e3f2.tar.gz
spray-json-derivation-eada4c48b3954241e130f5d9b5e7feebe8c1e3f2.tar.bz2
spray-json-derivation-eada4c48b3954241e130f5d9b5e7feebe8c1e3f2.zip
Prepare for releasing
-rwxr-xr-x.ci/build27
-rw-r--r--.ci/sec.gpg.encbin0 -> 2480 bytes
-rw-r--r--.travis.yml19
-rw-r--r--LICENSE67
-rw-r--r--README.md56
-rw-r--r--build.sbt10
-rw-r--r--project/plugins.sbt3
-rw-r--r--src/main/scala/CustomFormats.scala19
-rw-r--r--src/main/scala/DerivedFormats.scala119
-rw-r--r--src/main/scala/annotations.scala33
-rw-r--r--src/main/scala/main.scala58
-rw-r--r--src/test/scala/CoproductTypeFormats.scala58
-rw-r--r--src/test/scala/FormatTests.scala20
-rw-r--r--src/test/scala/ProductTypeFormats.scala54
14 files changed, 427 insertions, 116 deletions
diff --git a/.ci/build b/.ci/build
new file mode 100755
index 0000000..2d42ac6
--- /dev/null
+++ b/.ci/build
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -ev
+
+sbt scalafmtTest +test
+
+# Automatic publishing for tags that start with `v<digit>`
+if [[ "$TRAVIS_PULL_REQUEST" == "false" && "$TRAVIS_TAG" =~ ^v[0-9].* ]]; then
+ # Setup gpg keys
+ gpg --keyserver keyserver.ubuntu.com --recv-key "DC7751D77486D755815C04AB488F99C904F077E8"
+ openssl aes-256-cbc -K "$encrypted_c6e2aee6c53f_key" -iv "$encrypted_c6e2aee6c53f_iv" -in .ci/sec.gpg.enc -out sec.gpg -d
+ gpg --import sec.gpg
+
+ # Set up publishing settings and credentials
+ cat <<EOF > credentials.sbt
+ useGpg := true
+ pgpSigningKey := Some(0x488F99C904F077E8l)
+ credentials += Credentials(
+ "Sonatype Nexus Repository Manager",
+ "oss.sonatype.org",
+ "vZKBpUCV",
+ "$SONATYPE_PASS"
+ )
+EOF
+
+ # Publish and release
+ sbt +publishSigned sonatypeRelease
+fi
diff --git a/.ci/sec.gpg.enc b/.ci/sec.gpg.enc
new file mode 100644
index 0000000..cd30d2f
--- /dev/null
+++ b/.ci/sec.gpg.enc
Binary files differ
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..6305657
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,19 @@
+language: scala
+
+jdk:
+ - oraclejdk8 # this should be changed to openjdk as soon as it becomes available on Travis CI
+
+env:
+ - secure: "KuhZl6+JNGag+CUHkbmbN8cnZ09fn+B8wVb8ZKG+z+RrofTkwCOfnCNpC6PZb8ZPP+1YkM9oxfo6xah22e4XE2Viu17GQeFRG56C2Pe/XEpaNLfxitu3c2rx2+3GVlYHKCEb0s1ZLkV7gtJcO5PHgtH6fXJ9FqEqQ/5bOLo6xduhytNwIxoLseZn3581yF4dAYtOxm9ebj9mbFMqx/twdYLvEVu+ePIrqACwZUNcpR9dQxEPxQs7CVkwTnMzGMxkPGe1RoFPyhPIPhY8X6mW4Gc75riY9aFoI6gFvyyrAjOPoC7zwZyqSZSzxjkFAxXtpsHhkA05GeLvw1wLh2FOHxFwR5WU92DgvF1slQ4b4XDXxXjLlCJo3g98WtshFspXvdalrNKQJ92CroNtLusbkVfv1N8cILgA7kkCAVN7L+l76duiXwAunUI0poOMO+oBEU4NcHe4de4Ef9dmXTPU/kFyAYZsPHkRH/fcJEuEex3haFzvRv9g/OvKleXvprVJhMYC2zsagW2c8h1gjBT2P5DUNB6V6jV5XprN4ATbIwpJBlGGOxZ/6gspVKc2m6exq0DN0mmx160BMwR1wHvYbCUEY5hMrg5e4x9KmVIF8BQd4v0dvihRpYCkz2RfAk6viSJjsAAyOUswfY2AcONbBjYDvCFsKiSQGJHS+RJjZ2M="
+
+script: .ci/build
+
+cache:
+ directories:
+ - "$HOME/.ivy2/cache"
+ - "$HOME/.sbt/boot/"
+
+before_cache:
+ - find $HOME/.ivy2/cache/xyz.driver -depth -name "tracing*" -exec rm -r {} \;
+ - find $HOME/.ivy2 -name "ivydata-*.properties" -delete
+ - find $HOME/.sbt -name "*.lock" -delete
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..9aa0a58
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,67 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License.
+
+Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License.
+
+Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution.
+
+You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of this License; and
+You must cause any modified files to carry prominent notices stating that You changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions.
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks.
+
+This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty.
+
+Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability.
+
+In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability.
+
+While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS \ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1aefe7b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,56 @@
+[![Build Status](https://travis-ci.org/drivergroup/spray-json-derivation.svg?branch=master)](https://travis-ci.org/drivergroup/spray-json-derivation)
+[![Download](https://img.shields.io/maven-central/v/xyz.driver/spray-json-derivation_2.12.svg)](http://search.maven.org/#search|ga|1|xyz.driver%20spray-json-derivation-)
+
+# Spray JSON Format Derivation
+
+This library provides automatic spray JsonFormats for any `case class` and children of `sealed trait`s.
+
+It uses the [Magnolia](http://magnolia.work/) ([source code](https://github.com/propensive/magnolia)) type-derivation library to implicitly generate JSON formats for any product type. Magnolia integrates with spray so seamlessly that it is almost not worth the effort to publish this project as a full fledged repository; a single gist with the contents of [DerivedFormats.scala](src/main/scala/DerivedFormats.scala) would provide almost all functionality.
+
+## Getting Started
+
+Spray JSON Format Derivation is published to maven central as a Scala
+library. Include it in sbt by adding the following snippet to your
+build.sbt:
+
+```scala
+libraryDependencies += "xyz.driver" %% "spray-json-derivation" % "<latest version>"
+```
+
+Define some case classes and mix `DerivedFormats` into your JSON
+protocol stack. That's it.
+
+```
+import spray.json._
+import xyz.driver.json.DerivedFormats
+
+object Main extends App with DefaultJsonProtocol with DerivedFormats {
+
+ case class A(x: Int)
+ case class B(a: A, str: String)
+
+ println(B(A(42), "hello world").toJson.prettyPrint)
+
+}
+```
+
+
+## Documentation
+Check out the main file
+[DerivedFormats.scala](src/main/scala/DerivedFormats.scala) and the
+test suite for a complete overview of the project.
+
+## Copying
+Copyright 2018 Driver Inc.
+
+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.
diff --git a/build.sbt b/build.sbt
index 750289a..75434fe 100644
--- a/build.sbt
+++ b/build.sbt
@@ -1,4 +1,10 @@
+name := "spray-json-derivation"
+organization := "xyz.driver"
-libraryDependencies += "io.spray" %% "spray-json" % "1.3.4"
+scalaVersion := "2.12.4"
-libraryDependencies += "com.propensive" %% "magnolia" % "0.6.1"
+libraryDependencies ++= Seq(
+ "io.spray" %% "spray-json" % "1.3.4",
+ "com.propensive" %% "magnolia" % "0.6.2-SNAPSHOT",
+ "org.scalatest" %% "scalatest" % "3.0.2"
+)
diff --git a/project/plugins.sbt b/project/plugins.sbt
new file mode 100644
index 0000000..a1e2f8a
--- /dev/null
+++ b/project/plugins.sbt
@@ -0,0 +1,3 @@
+ivyLoggingLevel := UpdateLogging.Quiet
+
+addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.2.0")
diff --git a/src/main/scala/CustomFormats.scala b/src/main/scala/CustomFormats.scala
deleted file mode 100644
index 3656e3b..0000000
--- a/src/main/scala/CustomFormats.scala
+++ /dev/null
@@ -1,19 +0,0 @@
-
-import spray.json._
-
-trait CustomFormats extends DefaultJsonProtocol {
-
- implicit val fooFormat: JsonFormat[Foo] = new JsonFormat[Foo] {
- def read(number: JsValue) = number match {
- case JsNumber(x) => Foo(-x.toInt)
- case tpe => sys.error(s"no way I'm reading that type $tpe!")
- }
- def write(number: Foo) = JsNumber(-number.x)
- }
-
- implicit val z: JsonFormat[B] = new JsonFormat[B] {
- def read(x: JsValue) = B("gone")
- def write(x: B) = JsObject("a" -> JsString("A"))
- }
-
-}
diff --git a/src/main/scala/DerivedFormats.scala b/src/main/scala/DerivedFormats.scala
index 6c2396e..79c1e4d 100644
--- a/src/main/scala/DerivedFormats.scala
+++ b/src/main/scala/DerivedFormats.scala
@@ -1,55 +1,100 @@
+package xyz.driver.json
+
import magnolia._
import spray.json._
import scala.language.experimental.macros
-trait JsonFormatDerivation extends DefaultJsonProtocol {
+trait DerivedFormats { self: BasicFormats =>
type Typeclass[T] = JsonFormat[T]
- def combine[T](ctx: CaseClass[JsonFormat, T]): JsonFormat[T] = new JsonFormat[T] {
- override def write(value: T): JsValue = {
- val fields: Seq[(String, JsValue)] = ctx.parameters.map { param =>
- param.label -> param.typeclass.write(param.dereference(value))
- }
- JsObject(fields: _*)
- }
- override def read(value: JsValue): T = value match {
- case obj: JsObject =>
- ctx.construct { param =>
- param.typeclass.read(obj.fields(param.label))
+ def combine[T](ctx: CaseClass[JsonFormat, T]): JsonFormat[T] =
+ new JsonFormat[T] {
+ override def write(value: T): JsValue =
+ if (ctx.isObject) {
+ JsString(ctx.typeName.short)
+ } else {
+ val fields: Seq[(String, JsValue)] = ctx.parameters.map { param =>
+ param.label -> param.typeclass.write(param.dereference(value))
+ }
+ JsObject(fields: _*)
}
- case js =>
- deserializationError(s"Cannot read JSON '$js' as a ${ctx.typeName}")
- }
- }
- def dispatch[T](ctx: SealedTrait[JsonFormat, T]): JsonFormat[T] = new JsonFormat[T] {
- override def write(value: T): JsValue = {
- ctx.dispatch(value) { sub =>
- val obj = sub.typeclass.write(sub.cast(value)).asJsObject
- JsObject((obj.fields ++ Map("type" -> JsString(sub.label))).toSeq: _*)
+ override def read(value: JsValue): T = value match {
+ case obj: JsObject =>
+ ctx.construct { param =>
+ param.typeclass.read(obj.fields(param.label))
+ }
+ case str: JsString if ctx.isObject && str.value == ctx.typeName.short =>
+ ctx.rawConstruct(Seq.empty)
+
+ case js =>
+ deserializationError(
+ s"Cannot read JSON '$js' as a ${ctx.typeName.full}")
}
}
- override def read(value: JsValue): T = value match {
- case obj: JsObject if obj.fields.contains("type") =>
- val fieldName = obj.fields("type").convertTo[String]
-
- ctx.subtypes.find(_.label == fieldName) match {
- case Some(tpe) => tpe.typeclass.read(obj)
- case None =>
- deserializationError(
- s"Cannot deserialize JSON to ${ctx.typeName} because type field '${fieldName}' has an unsupported value.")
- }
- case js =>
- deserializationError(s"Cannot read JSON '$js' as a ${ctx.typeName}")
- }
+ def dispatch[T](ctx: SealedTrait[JsonFormat, T]): JsonFormat[T] =
+ new JsonFormat[T] {
+ def tpe =
+ ctx.annotations
+ .find(_.isInstanceOf[JsonAnnotation])
+ .getOrElse(new gadt("type"))
+
+ override def write(value: T): JsValue = tpe match {
+ case _: enum =>
+ ctx.dispatch(value) { sub =>
+ JsString(sub.typeName.short)
+ }
- }
+ case g: gadt =>
+ ctx.dispatch(value) { sub =>
+ val obj = sub.typeclass.write(sub.cast(value)).asJsObject
+ JsObject(
+ (Map(g.typeFieldName -> JsString(sub.typeName.short)) ++
+ obj.fields).toSeq: _*)
+ }
+ }
+
+ override def read(value: JsValue): T = tpe match {
+ case _: enum =>
+ value match {
+ case str: JsString =>
+ ctx.subtypes
+ .find(_.typeName.short == str.value)
+ .getOrElse(deserializationError(
+ s"Cannot deserialize JSON to ${ctx.typeName.full} because " +
+ "type '${str}' has an unsupported value."))
+ .typeclass
+ .read(str)
+ case js =>
+ deserializationError(
+ s"Cannot read JSON '$js' as a ${ctx.typeName.full}")
+ }
+
+ case g: gadt =>
+ value match {
+ case obj: JsObject if obj.fields.contains(g.typeFieldName) =>
+ val fieldName = obj.fields(g.typeFieldName).convertTo[String]
+
+ ctx.subtypes.find(_.typeName.short == fieldName) match {
+ case Some(tpe) => tpe.typeclass.read(obj)
+ case None =>
+ deserializationError(
+ s"Cannot deserialize JSON to ${ctx.typeName.full} " +
+ s"because type field '${fieldName}' has an unsupported " +
+ "value.")
+ }
+
+ case js =>
+ deserializationError(
+ s"Cannot read JSON '$js' as a ${ctx.typeName}")
+ }
+ }
+ }
implicit def gen[T]: JsonFormat[T] = macro Magnolia.gen[T]
}
-object JsonFormatDerivation extends JsonFormatDerivation
-trait DerivedFormats extends JsonFormatDerivation
+object DerivedFormats extends DerivedFormats with BasicFormats
diff --git a/src/main/scala/annotations.scala b/src/main/scala/annotations.scala
new file mode 100644
index 0000000..f23fbcb
--- /dev/null
+++ b/src/main/scala/annotations.scala
@@ -0,0 +1,33 @@
+package xyz.driver.json
+
+import scala.annotation.StaticAnnotation
+
+/** Indicator trait of anontations related to JSON formatting. */
+sealed trait JsonAnnotation
+
+/** An annotation that designates that a sealed trait is a generalized algebraic
+ * datatype (GADT), and that a type field containing the serialized childrens'
+ * types should be added to the final JSON objects.
+ *
+ * Note that by default all sealed traits are treated as GADTs, with a type
+ * field called `type`. This annotation enables overriding the name of that
+ * field and is really only useful if a child itself has a field called `type`
+ * that would result in a conflict.
+ *
+ * Example
+ * ```
+ * // the JSON field "kind" will contain the actual type of the serialized child
+ * @gadt("kind") sealed abstract class Keyword(`type`: String)
+ * case class If(`type`: String) extends Keyword(`type`)
+ * ```
+ *
+ * @param typeFieldName the name of the field to inject into a serialized JSON
+ * object */
+final class gadt(val typeFieldName: String = "type")
+ extends StaticAnnotation
+ with JsonAnnotation
+
+/** An annotation that designates that a sealed trait is an enumeration (all
+ * children are strictly case objects), and that all children should be
+ * serialized as strings. */
+final class enum extends StaticAnnotation with JsonAnnotation
diff --git a/src/main/scala/main.scala b/src/main/scala/main.scala
deleted file mode 100644
index 223ac1c..0000000
--- a/src/main/scala/main.scala
+++ /dev/null
@@ -1,58 +0,0 @@
-import spray.json._
-
-// product type
-case class Foo(x: Int)
-case class Bar(foo: Foo, str: String)
-
-// coproduct
-sealed trait T
-case object A extends T
-case class B(a: String) extends T
-case class C(x: T) extends T // inception!
-
-object Main extends App with DefaultJsonProtocol with DerivedFormats {
-
- println("//////////\nProducts:")
-
- {
- val product = Bar(Foo(42), "hello world")
- val js = product.toJson
- println(js.prettyPrint)
- println(js.convertTo[Bar])
- }
-
- println("//////////\nCoproducts:")
-
- {
- val coproduct: T = B("hello wordld") //Seq(C(B("What's up?")), B("a"), A)
- val js = coproduct.toJson
- println(js.prettyPrint)
- println(js.convertTo[T])
- }
-
-}
-
-/*
-A potentital danger:
-
-Overriding generated formats is possible (see CustomFormats), however it can be
-easy to forget to include the custom formats.
-=> In that case, the program will still compile, however it won't use the
- correct format!
-
-Possible workarounds?
-
- - Require explicit format declarations, i.e. remove implicit from `implicit def
- gen[T] = macro Magnolia.gen[T]` and add `def myFormat = gen[Foo]` to every
- format trait.
- => requires manual code, thereby mostly defeats the advantages of automatic derivation
- => (advantage, no more code duplication since macro is expanded only once)
-
- - Avoid custom formats.
- => entities become "API objects", which will be hard to upgrade in a backwards-compatible, yet idiomatic way
- (E.g. new fields could be made optional so that they won't be required in json, however the business logic
- may not require them to be optional. We lose some typesafety.)
- => we'd likely have an additional layer of indirection, that will convert "api objects" to "business objects"
- implemented by services
- => Is that a good or bad thing?
-*/
diff --git a/src/test/scala/CoproductTypeFormats.scala b/src/test/scala/CoproductTypeFormats.scala
new file mode 100644
index 0000000..f16e4c7
--- /dev/null
+++ b/src/test/scala/CoproductTypeFormats.scala
@@ -0,0 +1,58 @@
+package xyz.driver.json
+
+import spray.json._
+
+import org.scalatest._
+
+class CoproductTypeFormats
+ extends FlatSpec
+ with FormatTests
+ with DefaultJsonProtocol
+ with DerivedFormats {
+
+ sealed trait Expr
+ case class Zero() extends Expr
+ case class Value(x: Int) extends Expr
+ case class Plus(lhs: Expr, rhs: Expr) extends Expr
+ case object One extends Expr
+
+ "No-parameter case class child" should behave like checkCoherence[Expr](
+ Zero(),
+ """{"type":"Zero"}"""
+ )
+
+ "Simple parameter case class child" should behave like checkCoherence[Expr](
+ Value(42),
+ """{"type":"Value","x":42}"""
+ )
+
+ "Nested parameter case class child" should behave like checkCoherence[Expr](
+ Plus(Value(42), Value(0)),
+ """{"type":"Plus","lhs":{"type":"Value","x":42},"rhs":{"type":"Value","x":0}}"""
+ )
+
+ // "Case object child" should behave like checkCoherence[Expr](
+ // One,
+ // """{"type":"One"}"""
+ // )
+
+ @gadt("kind")
+ sealed abstract class Keyword(`type`: String)
+ case class If(`type`: String) extends Keyword(`type`)
+
+ "GADT with type field alias" should behave like checkCoherence[Keyword](
+ If("class"),
+ """{"kind":"If","type":"class"}"""
+ )
+
+ @enum
+ sealed trait Enum
+ case object A extends Enum
+ case object B extends Enum
+
+ "Enum" should behave like checkCoherence[List[Enum]](
+ A :: B :: Nil,
+ """["A", "B"]"""
+ )
+
+}
diff --git a/src/test/scala/FormatTests.scala b/src/test/scala/FormatTests.scala
new file mode 100644
index 0000000..e29e49f
--- /dev/null
+++ b/src/test/scala/FormatTests.scala
@@ -0,0 +1,20 @@
+package xyz.driver.json
+
+import spray.json._
+import org.scalatest._
+
+trait FormatTests { self: FlatSpec =>
+
+ def checkCoherence[A: JsonFormat](a: A, expectedJson: String) = {
+ it should "serialize to the expected JSON value" in {
+ val expected: JsValue = expectedJson.parseJson
+ assert(a.toJson == expected)
+ }
+
+ it should "serialize then deserialize back to itself" in {
+ val reread = a.toJson.convertTo[A]
+ assert(reread == a)
+ }
+ }
+
+}
diff --git a/src/test/scala/ProductTypeFormats.scala b/src/test/scala/ProductTypeFormats.scala
new file mode 100644
index 0000000..9755198
--- /dev/null
+++ b/src/test/scala/ProductTypeFormats.scala
@@ -0,0 +1,54 @@
+package xyz.driver.json
+
+import spray.json._
+
+import org.scalatest._
+
+class ProductTypeFormats
+ extends FlatSpec
+ with FormatTests
+ with DerivedFormats
+ with DefaultJsonProtocol {
+
+ case class A()
+ case class B(x: Int, b: String, mp: Map[String, Int])
+ case class C(b: B)
+ case object D
+ case class E(d: D.type)
+ case class F(x: Int)
+
+ "No-parameter product" should behave like checkCoherence(A(), "{}")
+
+ "Simple parameter product" should behave like checkCoherence(
+ B(42, "Hello World", Map("a" -> 1, "b" -> -1024)),
+ """{ "x": 42, "b": "Hello World", "mp": { "a": 1, "b": -1024 } }"""
+ )
+
+ "Nested parameter product" should behave like checkCoherence(
+ C(B(42, "Hello World", Map("a" -> 1, "b" -> -1024))),
+ """{"b" :{ "x": 42, "b": "Hello World", "mp": { "a": 1, "b": -1024 } } }"""
+ )
+
+ "Case object" should behave like checkCoherence(
+ D,
+ """"D""""
+ )
+
+ "Case object as parameter" should behave like checkCoherence(
+ E(D),
+ """{"d":"D"}"""
+ )
+
+ // custom format for F, that inverts the value of parameter x
+ implicit val fFormat: JsonFormat[F] = new JsonFormat[F] {
+ override def write(f: F): JsValue = JsObject("x" -> JsNumber(-f.x))
+ override def read(js: JsValue): F =
+ F(-js.asJsObject.fields("x").convertTo[Int])
+ }
+
+ "Overriding with a custom format" should behave like checkCoherence(
+ F(2),
+ """{"x":-2}"""
+ )
+
+}