score:27

Accepted answer

writes isn't a covariant functor, so you can't use map, but you can use contramap:

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit val someclasswrites: writes[someclass] =
  (__ \ 'foo).writenullable[double].contramap(_.foo)

if you have more than one member, you can use play's functionalbuilder syntax:

case class anotherclass(foo: option[double], bar: option[string])

implicit val anotherclasswrites: writes[anotherclass] = (
  (__ \ 'foo).writenullable[double] and
  (__ \ 'bar).writenullable[string]
)(ac => (ac.foo, ac.bar))

in the first case the argument to contramap is just a function from the type you want a writes for to the type in the writes you're calling contramap on. in the second case, the function at the end is from the target (anotherclass here) to a tuple of the writes instances you've built up with and (in this case option[double] and option[string]).

score:2

the easy way is:

import play.api.libs.json.json

implicit val fmt = json.format[someclass]

which uses a macro to auto-generate the json format for you. beats implementing writes directly.


Related Query

More Query from same tag