aboutsummaryrefslogtreecommitdiff
path: root/shared/src/main
diff options
context:
space:
mode:
authorJakob Odersky <jakob@driver.xyz>2018-06-29 17:56:06 -0700
committerJakob Odersky <jakob@odersky.com>2018-07-02 16:28:46 -0700
commitc5c1aa6bc78b6ebc346befe9f4b434401a683a59 (patch)
treefd5a92d7b89825d68496306d81dc7ebd2b2f1981 /shared/src/main
parent1c358416737f8e7d41d6858000ce07680df7afee (diff)
downloadspray-json-derivation-c5c1aa6bc78b6ebc346befe9f4b434401a683a59.tar.gz
spray-json-derivation-c5c1aa6bc78b6ebc346befe9f4b434401a683a59.tar.bz2
spray-json-derivation-c5c1aa6bc78b6ebc346befe9f4b434401a683a59.zip
Make inclusion of None values as null optional
Diffstat (limited to 'shared/src/main')
-rw-r--r--shared/src/main/scala/DerivedFormats.scala19
1 files changed, 15 insertions, 4 deletions
diff --git a/shared/src/main/scala/DerivedFormats.scala b/shared/src/main/scala/DerivedFormats.scala
index 6ea7c4b..ccf48d1 100644
--- a/shared/src/main/scala/DerivedFormats.scala
+++ b/shared/src/main/scala/DerivedFormats.scala
@@ -13,13 +13,24 @@ trait DerivedFormats { self: BasicFormats =>
* method can be overriden to use alternative naming conventions. */
@inline def extractFieldName(paramName: String): String = paramName
+ /** Determines if `None` instances of options should be included in JSON output.
+ *
+ * By default, `None` values are ommitted entirely from resulting JSON
+ * objects. If overridden, they will be included as `null`s instead.
+ *
+ * Note that this has no effect in *reading* option types; undefined or null
+ * values are always converted to `None`. */
+ def printNull: Boolean = false
+
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 =>
- extractFieldName(param.label) -> param.typeclass.write(
- param.dereference(value)
- )
+ val fields: Seq[(String, JsValue)] = ctx.parameters.collect {
+ case param
+ if !param.option || param.dereference(value) != None || printNull =>
+ extractFieldName(param.label) -> param.typeclass.write(
+ param.dereference(value)
+ )
}
JsObject(fields: _*)
}