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

假如想象 提交于 2020-08-08 14:50:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!