限制在 JSON 端点中返回的字段

Limiting the fields returning in a JSON endpoint

我有一个端点,我希望允许调用者限制 JSON 结果中返回的字段数。

case class User(id: Int, p1: String, p2: String, p3: Int, p4: Boolean, ...)

控制器动作看起来像:

 def index() = Action { implicit request: Request[AnyContent] =>
    val user = userService.get(...)
    Ok(user)
  }

所以说端点可以这样调用:

/user/123
/user/123?fields=p1,p3

因为我有一个用户案例 class,我怎么可能根据调用者想要返回的内容以动态方式操作结果集?

仅过滤 JSON 个字段:

case class Lorem(foo: String, bar: Int)

implicit val format: OFormat[Lorem] = Json.format

val fields = List("foo")

Ok(JsObject(
  Json.toJsObject(Lorem("str", 2)).value.filterKeys(fields.contains)))

//{"foo":"str"}