How to write a Play JSON writes converter for a case class with a single nullable member

前端 未结 2 1092
鱼传尺愫
鱼传尺愫 2020-12-29 10:56

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 conver

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 11:31

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

提交回复
热议问题