I'm using play-json's macros to define implicit Writes
for serializing JSON. However, it seems like by default play-json omits fields for which Option
fields are set to None
. Is there a way to change the default so that it outputs null
instead? I know this is possible if I define my own Writes
definition, but I'm interested in doing it via macros to reduce boilerplate code.
Example
case class Person(name: String, address: Option[String])
implicit val personWrites = Json.writes[Person]
Json.toJson(Person("John Smith", None))
// Outputs: {"name":"John Smith"}
// Instead want to output: {"name":"John Smith", "address": null}
implicit class WritesOps[A](val self: OWrites[A]) extends AnyVal { def ensureFields(fieldNames: String*)(value: JsValue = JsNull, path: JsPath = _): OWrites[A] ={ def tf(o: JsObject): JsObject = o ++ JsObject(fieldNames.withFilter(v => !o.keys.contains(v)).map( -> value)(collection.breakOut)) self.transform(tf(_)) } }
– Imbecility