Blankman
Blankman

Reputation: 267190

Limiting the fields returning in a JSON endpoint

I have an endpoint where I want to allow the caller to limit the # of fields returned in the JSON result.

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

controller action looks like:

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

So say the endpoint can be called like:

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

Since I have a user case class, how could I possible manipulate the result set in a dynamic way based on what the caller wants returned?

Upvotes: 0

Views: 35

Answers (1)

cchantep
cchantep

Reputation: 9168

Just filter JSON fields:

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

Upvotes: 1

Related Questions