aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJakob Odersky <jakob@odersky.com>2018-03-29 13:11:43 -0700
committerJakob Odersky <jakob@odersky.com>2018-04-17 22:36:20 -0700
commit83942244b48d8f7a68ecdaade90b92a79378d43c (patch)
treeaa12e0ae1d69e27dae645cd50e545d6551e2497e
parent4e50db580a11468cd12cfb4374a8825f88b3c090 (diff)
downloadspray-json-derivation-83942244b48d8f7a68ecdaade90b92a79378d43c.tar.gz
spray-json-derivation-83942244b48d8f7a68ecdaade90b92a79378d43c.tar.bz2
spray-json-derivation-83942244b48d8f7a68ecdaade90b92a79378d43c.zip
Allow deserialization of option fields if they are omitted
Fixes #5
-rw-r--r--build.sbt2
-rw-r--r--shared/src/main/scala/DerivedFormats.scala7
-rw-r--r--shared/src/test/scala/ProductTypeFormatTests.scala17
3 files changed, 24 insertions, 2 deletions
diff --git a/build.sbt b/build.sbt
index 9f99ddb..0954c0a 100644
--- a/build.sbt
+++ b/build.sbt
@@ -20,7 +20,7 @@ lazy val sprayJsonDerivation =
),
libraryDependencies ++= Seq(
"io.crashbox" %%% "spray-json" % "1.3.4-1",
- "com.propensive" %%% "magnolia" % "0.7.1"
+ "io.crashbox" %%% "magnolia" % "0.7.1-1"
)
)
.platformsSettings(JVMPlatform, JSPlatform)(
diff --git a/shared/src/main/scala/DerivedFormats.scala b/shared/src/main/scala/DerivedFormats.scala
index d0cac38..eabfa82 100644
--- a/shared/src/main/scala/DerivedFormats.scala
+++ b/shared/src/main/scala/DerivedFormats.scala
@@ -24,7 +24,12 @@ trait DerivedFormats { self: BasicFormats =>
ctx.rawConstruct(Seq.empty)
} else {
ctx.construct { param =>
- param.typeclass.read(obj.fields(param.label))
+ val fieldValue = if (param.option) {
+ obj.fields.getOrElse(param.label, JsNull)
+ } else {
+ obj.fields(param.label)
+ }
+ param.typeclass.read(fieldValue)
}
}
case js =>
diff --git a/shared/src/test/scala/ProductTypeFormatTests.scala b/shared/src/test/scala/ProductTypeFormatTests.scala
index ce05000..502568f 100644
--- a/shared/src/test/scala/ProductTypeFormatTests.scala
+++ b/shared/src/test/scala/ProductTypeFormatTests.scala
@@ -74,4 +74,21 @@ class ProductTypeFormatTests
"""{"h": {"x":true}}"""
)
+ case class Opt(x: Option[Int])
+ implicit val optFmt = jsonFormat[Opt]
+
+ "Option fields with some value" should behave like checkRoundtrip(
+ Opt(Some(2)),
+ """{"x":2}"""
+ )
+
+ "Option fields with null value" should behave like checkRoundtrip(
+ Opt(None),
+ """{"x":null}"""
+ )
+
+ "Option fields with undefined value" should "deserialize" in {
+ assert("{}".parseJson.convertTo[Opt] == Opt(None))
+ }
+
}