问题
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).
回答1:
Simply remove the password field from your Writes
:
implicit val userWrites: Writes[User] = Writes { user =>
Json.obj(
"id" -> user.id,
"username" -> user.username
)
}
来源:https://stackoverflow.com/questions/39089851/play-framework-how-to-ignore-some-fields-for-json-serialisation