5

I have case class

case class User (
  id: Option[Long] = None,
  username: String,     
  password: Option[String] = None,
)

And here is json serialiser for this case class

object User {
  implicit val userWrites: Writes[User] = (
      (JsPath \ "id").write[Option[Long]] and
      (JsPath \ "username").write[String] and     
      (JsPath \ "password").write[Option[String]] and
    )(unlift(User.unapply))
}

But I don't want to expose password field in api response. How can I achieve it?

I use also use this for Slick to read/write data in appropriate table, I'm using it in many places, service layer, controller layer, and I don't want to create separate class for api response (without password).

Teimuraz
  • 8,795
  • 5
  • 35
  • 62

1 Answers1

9

Simply remove the password field from your Writes:

implicit val userWrites: Writes[User] = Writes { user =>
  Json.obj(
    "id" -> user.id,
    "username" -> user.username
  )
}
vdebergue
  • 2,354
  • 16
  • 19
  • thank you, different syntax, but it works. I've tried to remove password field from my example above, but it didn't compile, why is that? – Teimuraz Aug 23 '16 at 09:41
  • That's because of the unapply, the number of arguments will not match if you remove the password field, you would have to modify the part `(unlift(User.unapply))`. I prefer this syntax as it's easier to read and access the field of your object – vdebergue Aug 23 '16 at 11:17