Play Framework - 如何忽略 Json 序列化的某些字段? [英] Play Framework - how to ignore some fields for Json Serialisation?

查看:51
本文介绍了Play Framework - 如何忽略 Json 序列化的某些字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有案例类

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

这里是这个案例类的 json 序列化器

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

但我不想在 api 响应中公开 password 字段.我怎样才能实现它?

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

我也使用它来为 Slick 在适当的表中读/写数据,我在很多地方使用它,服务层,控制器层,我不想为 api 响应创建单独的类(没有密码).

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

推荐答案

只需从 Writes 中删除密码字段:

Simply remove the password field from your Writes:

implicit val userWrites: Writes[User] = Writes { user =>
  Json.obj(
    "id" -> user.id,
    "username" -> user.username
  )
}

这篇关于Play Framework - 如何忽略 Json 序列化的某些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆