Skip to content

Instantly share code, notes, and snippets.

@nraychaudhuri
Last active December 11, 2015 19:48
Show Gist options
  • Save nraychaudhuri/4650941 to your computer and use it in GitHub Desktop.
Save nraychaudhuri/4650941 to your computer and use it in GitHub Desktop.
Play JSON example. Parse post json body using the body parser, use implicit format to convert it to case class and then send back json response
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json._
object Application extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
case class Foo(one: String, two: Int)
//format object used to convert json to case class Foo
implicit val fooFormat: Format[Foo] = Json.format[Foo]
def handleJsonRequest = Action(BodyParsers.parse.json) { request =>
//using the body parser to parse request body to json
val jsonBody: JsValue = request.body
//converting json to case class
val foo : Foo = jsonBody.as[Foo]
println(s"case class ${foo}")
//making some modification to case class
val anotherFoo = foo.copy(one = "This is a new value")
//converting back to json
val anotherJson: JsValue = Json.toJson(anotherFoo)
//sending the json response
Ok(anotherJson)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment