Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 543 posts at DZone. You can read more from them at their website. View Full User Profile

Play Framework 2.0: Rendering JSON data in the view

10.26.2012
| 8991 views |
  • submit to reddit

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:

[{"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))};
</script>

 

And now the JSON renders beautifully!

 

 

 

 

Published at DZone with permission of Mark Needham, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)