julienrf / play-json-derived-codecs

MIT License
191 stars 34 forks source link

Output null for None values #64

Open d6y opened 5 years ago

d6y commented 5 years ago

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).

julienrf commented 5 years ago

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)!

d6y commented 5 years ago

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 šŸ»