O'Reilly logo

RESTful Web Services with Scala by Jos Dirksen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding JSON marshalling, validations, and error handling

As we've seen with the other frameworks, an important feature of a REST framework is the support for JSON. With Play 2, adding JSON is very easy. All it takes is defining the following implicits:

implicit val fmtNote = Json.format[Note]
implicit val fmtPerson = Json.format[Person]
implicit val fmtMStatus = Json.format[MStatus]
implicit val fmtTask = Json.format[Task]

With these implicits in scope, we can convert the relevant case classes to and from JSON by using the following two functions:

  • Json.toJson(obj): This converts the provided obj instance to JSON. This works if we've defined a Format object for that case class as we've done earlier.
  • request.body.asJson.map(_.as[Task]): Converting from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required