Creating class case letters and formats

In this case, the class:

case class People(names: Set[Int])

Travis Brown explained how to create PeopleReads: Reads[People]this:

implicit val PeopleReads = 
       (__ \ "names").read[Set[Id]].map(People)

But I am trying to implement PeopleWrites: Writes[People]:

 implicit val PeopleWrites: Writes[People] = 
    (JsPath \  "names").write[Set[Int]].map(unlift(x => Some((x.names)))

with the following compile time error:

scala> People( Set(1,2,3))
res5: People = People(Set(1, 2, 3))

scala>  implicit val PeopleWrites: Writes[People] = 
      (JsPath \  "names").write[Set[Int]].map(unlift(x => Some((x.names))))
<console>:21: error: value map is not a member of 
                play.api.libs.json.OWrites[Set[Int]]
              implicit val PeopleWrites: Writes[People] = 
                (JsPath \  "names").write[Set[Int]].
                                      map(unlift(x => Some((x.names)))

How can I solve this error?

Also, how can I write Format[People]where I get / define both Reads, and Writes:

val peopleFormat: Format[People] = ...?

+1
source share
1 answer

Good question! The reason you cannot use mapis because Writesit is not a functor.

Writes[A] - A => JsValue. , A => JsValue A => B. - , B => JsValue - .

Reads[A], , JsValue => A - map, A => B, Reads[A]/JsValue => A, a Reads[B]/JsValue => B.

Writes, , , , Play . F - , F[A] contramap[B](f: B => A) map[B](f: A => B). :

case class People(names: Set[Int])

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

implicit val PeopleWrites: Writes[People] =
  (__ \ 'names).write[Set[Int]].contramap(_.names)

(__ \ 'names).write[Set[Int]] Writes[Set[Int]], (_.names) - People => Set[Int]. contramap Writes[People].

+2

All Articles