play-json-derived-codecs icon indicating copy to clipboard operation
play-json-derived-codecs copied to clipboard

Output null for None values

Open d6y opened this issue 6 years ago • 2 comments

Hello šŸ‘‹

For a case class with an optional value set to None:

case class C(a: Int, z: Option[Int])
val c = C(1, None)

...is it possible to customise derive to preserve the None values in the JSON?

E.g., to get:

{  "a": 1, "z": null }

This is possibly related to the Play note on Customize the macro to output null (hmm, if that link doesn't take you to the right section, scroll to the bottom of the page).

d6y avatar May 15 '19 16:05 d6y

Hey, the way it is currently implemented is not configurable: https://github.com/julienrf/play-json-derived-codecs/blob/master/library/src/main/scala/julienrf/json/derived/DerivedOWrites.scala#L37-L44.

Maybe it is possible to do what you want by introducing a custom implicit rule and playing with the priorities to get it right!

Otherwise, I’m happy to merge a PR making this behaviour configurable (like we currently do with the NameAdapter and TypeTagOWrites)!

julienrf avatar May 15 '19 20:05 julienrf

Thank you @julienrf

Looks like I can implement a local scope version of owritesLabelledHListOpt and replace...

case None => Map.empty

...with...

case None => Map(adaptedName -> JsNull)

...to get the behaviour I need in this case šŸ»

d6y avatar May 16 '19 09:05 d6y