Mark Needham

Thoughts on Software Development

Play Framework 2.0: Rendering JSON data in the view

with one comment

I’ve been playing around with the Play Framework which we’re using to front a bunch of visualisations and one thing I wanted to do is send a data structure to a view and then convert that into JSON.

I’ve got a simple controller which looks like this:

package controllers;
 
import play.mvc.Controller;
import play.mvc.Result;
import views.html.*;
 
public class SalesByCategory extends Controller {
    public static Result index() {
        ArrayList<Map<String, Object>> series = new ArrayList<Map<String, Object>>();
        Map<String, Object> oneSeries = new HashMap<String, Object>();
        oneSeries.put("name", "awesome");
        oneSeries.put("sales", calculateSales()); # would call a method elsewhere, implementation isn't important
 
        series.add(oneSeries);
 
        # I have a view named 'index.scala.html'
        return ok(index.render("Awesome visualisation", series));
    }
}

The top of the corresponding view looks like this:

@(message: String)(series:List[Map[String, Object]])

I’m using the GSON library to convert objects into JSON so I need to import that into the view:

@import com.google.gson.Gson

I was initially struggling to work out what the syntax would be to call the GSON code from within the page but with a bit of trial and error realised that the following would do the trick:

<script lang="text/javascript">
  var series = @{new Gson().toJson(series)};
</script>

The problem with this version of the code was that the string was being escaped so I ended up with series having a value like this:

[{&quot;name&quot;:&quot; #and so on!

I needed to tell Play not to escape this string which in Play v1 was done by calling ‘raw()’ on the string but in Play v2 is done using the ‘Html’ method:

<script lang="text/javascript">
  var series = @{Html(new Gson().toJson(series))};
</script>

And now the JSON renders beautifully!

Be Sociable, Share!

Written by Mark Needham

October 14th, 2012 at 9:28 am

  • Anonymous

    I tried your solution, but I am getting the Execution Exception here is the log:

    [error] application –

    ! @6f080omfn – Internal server error, for (GET) [/races] ->

    play.api.Application$$anon$1: Execution exception[[RuntimeException: java.lang.StackOverflowError]]

    at play.api.Application$class.handleError(Application.scala:289) ~[play_2.10.jar:2.1.2]

    at play.api.DefaultApplication.handleError(Application.scala:383) [play_2.10.jar:2.1.2]

    at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$play$core$server$netty$PlayDefaultUpstreamHandler$$handle$1$1.apply(PlayDefaultUpstreamHandler.scala:143) [play_2.10.jar:2.1.2]

    at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$play$core$server$netty$PlayDefaultUpstreamHandler$$handle$1$1.apply(PlayDefaultUpstreamHandler.scala:139) [play_2.10.jar:2.1.2]

    at play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113) [play_2.10.jar:2.1.2]

    at play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113) [play_2.10.jar:2.1.2]

    java.lang.RuntimeException: java.lang.StackOverflowError

    at play.libs.F$Promise$6.apply(F.java:401) ~[play_2.10.jar:2.1.2]

    at scala.concurrent.Future$$anonfun$map$1.liftedTree2$1(Future.scala:253) ~[scala-library.jar:na]

    at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:249) ~[scala-library.jar:na]

    at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:249) ~[scala-library.jar:na]

    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:29) ~[scala-library.jar:na]

    at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.liftedTree1$1(BatchingExecutor.scala:67) ~[akka-actor_2.10.jar:na]

    java.lang.StackOverflowError: null

    at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:401) ~[na:na]

    at com.google.gson.stream.JsonWriter.beginObject(JsonWriter.java:307) ~[na:na]

    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:190) ~[na:na]

    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68) ~[na:na]

    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89) ~[na:na]

    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195) ~[na:na]