Over a million developers have joined DZone.

Play Framework 2.0: Rendering JSON data in the view

DZone's Guide to

Play Framework 2.0: Rendering JSON data in the view

· Java Zone ·
Free Resource

Take 60 minutes to understand the Power of the Actor Model with "Designing Reactive Systems: The Role Of Actors In Distributed Architecture". Brought to you in partnership with Lightbend.

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
        # 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)};

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:

[{"name":" #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))};


And now the JSON renders beautifully!





Learn how the Actor model provides a simple but powerful way to design and implement reactive applications that can distribute work across clusters of cores and servers. Brought to you in partnership with Lightbend.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}