Play Framework - how to ignore some fields for Json Serialisation?
Asked Answered
A

1

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

Anabal answered 22/8, 2016 at 22:47 Comment(0)
L
10

Simply remove the password field from your Writes:

implicit val userWrites: Writes[User] = Writes { user =>
  Json.obj(
    "id" -> user.id,
    "username" -> user.username
  )
}
Liminal answered 23/8, 2016 at 9:1 Comment(2)
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?Anabal
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 objectLiminal

© 2022 - 2024 — McMap. All rights reserved.