[Play-Java 2.6] Json data and template


#1

I’ve to plot a chart passing Json data to the template.
The data has to be in the following form:
data: [
{ y: ‘Turno A’, a: 100 },
{ y: ‘Turno B’, a: 75 },
{ y: ‘Turno C’, a: 50 },
{ y: ‘Turno D’, a: 75 }
]

In my Play controller I use the following method to create the Json object:

public Result statistics() {
        ArrayList<Map<Object, Serializable>> all = new ArrayList<Map<Object, Serializable>>();
        List<Tourn> t = tourn.findAll();
        for(Tourn tr: t) {
            Map<Object, Serializable> details = new HashMap<Object, Serializable>();
            details.put("y", tr.getName());
            details.put("a", student.countAllByTourn(tr.getName()));

            all.add(details);
        }

        System.out.println(all);
        return ok(statistics.render(play.libs.Json.toJson(all)));

    }e

It’s print:
[{a=2, y=Turno A}, {a=1, y=Turno B}]

In the template I have:

@import com.fasterxml.jackson.databind.JsonNode
@(all: JsonNode)

<script type="text/javascript">
        $(function() {
            Morris.Bar({
                element: 'flot-bar-chart',
                data: @all,
                xkey: 'y',
                ykeys: ['a'],
                labels: ['Turni',]
            });

        });

    </script>

But checking the source page the all variable was converted in:
data: [{&quot;a&quot;:2,&quot;y&quot;:&quot;Turno A&quot;},{&quot;a&quot;:1,&quot;y&quot;:&quot;Turno B&quot;}],

so the chart isn’t displayed.

Is there a solution for that?


(Aditya Athalye) #2

Try using data: decodeURI(@all) to un-escape the escape characters. Not sure if that will work syntactically, but the idea to un-escape those characters.

HTH
Aditya


#3

Doesn’t work.
Now in the source, I’ve:

data: decodeURI([{&quot;a&quot;:3,&quot;y&quot;:&quot;Turno A&quot;},{&quot;a&quot;:1,&quot;y&quot;:&quot;Turno B&quot;}]),


(Patrick Li) #4

Try @Html(all)


(Tanin Na Nakorn) #5

Also, be aware of cross-site scripting when using @Html(all). If your json contains </script><script> .. </script><script>, it’s gonna cause an issue.

I suggest encoding the data in Base64 and decode it in Javascript. An example is here: https://github.com/GIVESocialMovement/sbt-vuefy/blob/master/test-play-project/app/views/index.scala.html#L19


#6

This doesnt’ work:

type mismatch;
found : com.fasterxml.jackson.databind.JsonNode
required: String


(Tanin Na Nakorn) #7

Try @Html(all.toString)


#8

Thanks!!! It’s working