In Play 2.3, I have a case class with a single optional double member:
case class SomeClass(foo: Option[Double])
I need a JSON write converter that handles the member as nullable:
implicit val someClassWrite: Writes[SomeClass] = ???
The Play docs provide an example:
case class DisplayName(name:String)
implicit val displayNameWrite: Writes[DisplayName] = Writes {
(displayName: DisplayName) => JsString(displayName.name)
}
But sadly I can't figure out how to do this for 1) a single nullable and 2) a double. Any ideas? Thanks.
Update #1: The only solution I can come up with is this:
implicit val someClassWrite: Writes[SomeClass] = Writes {
(someClass: SomeClass) => someClass.foo match {
case Some(f) => JsNumber(BigDecimal(f))
case _ => JsNull
}
Update #2: Ignore my solution. Travis Brown's is the one.
The easy way is:
Which uses a macro to auto-generate the json format for you. Beats implementing writes directly.
Writes
isn't a covariant functor, so you can't usemap
, but you can usecontramap
:If you have more than one member, you can use Play's
FunctionalBuilder
syntax:In the first case the argument to
contramap
is just a function from the type you want aWrites
for to the type in theWrites
you're callingcontramap
on. In the second case, the function at the end is from the target (AnotherClass
here) to a tuple of theWrites
instances you've built up withand
(in this caseOption[Double]
andOption[String]
).