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 {
  Ok(Json.toJson(MyModel.findAll()))
}


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 {
  Ok(MyModel.findAll())
}


and actions dont the logic of converting to json anymore!

7 comments:

Tyke said...

Hello, your radio on sdr.hu site is really great, but why does it go Gateway 502 error for a long time. I was unable to contact you via the radio portal.

Thank you for your consideration.

Selva said...

Hi, I brought it up again. And have setup an alert to get notified when it goes down.
Enjoy!

Tyke said...

Hi Selva

Your SDR site has been offline for some time now. Really missing it here. Gateway 502 errors. Will it be coming back soon?

Thanks & kind regards.

Tyke

Selva said...

Hi, Im testing another radio intensive device which is sitting next to it and to avoid interference I have temporarily brought it down.
It would be up again in another few days.

Thanks for your interest.

FPLman said...

We are still patiently waiting its return! It is a great site and is being missed by many. I hope your device testing will be complete soon.

Selva said...

Hi @FPLman, I have brought it up again.
Im quite curious now, how do you and other are using it and finding it useful for.

FPLman said...

Mainly for listening to air traffic across the Arabian Sea and Bay of Bengal. 8879 is probably the busiest with airliner traffic but 8861 also good as often coastguard flights use that freq. 8861 is often a struggle to hear though as Chennai is often completely inaudible through your morning time and only Kolkata can be heard which doesn't control as much traffic. Myself and my friend in Holland would be happy to contribute towards any costs to make Chennai audible on your radio fyi. Thanks so much for putting it back online!