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

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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!





BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}