Friday, May 16, 2014

Default serializer in play framework for Json responses

In playframework (Scala), typically in a controller when you want to render json responses, you do something like:

def index = Action {

Looks simple, but the problem is the Json.toJson repeated in all the controller cannot be pulled to a common method, because of the different response status codes like Ok or Created etc.

A better and less verbose way would be specifying the concern of converting to Json in a common place (like ApplicationController or somewhere).

One way of achieving this would be using scala implicit methods, just by defining this in the application controller:

implicit def writeableOfAny(implicit codec: Codec): Writeable[Any] = Writeable(data =>
  Json.toJson(data).toString.getBytes, Some(ContentTypes.JSON))

By this, we are instructing playframework to use this method as the implicit way to convert any object to writable stream, which is sent back as http response.

With this, the action would simply be:

def index = Action {

and actions dont the logic of converting to json anymore!