Search code examples
javascriptjavaarraysrhinonashorn

Nashorn/Rhino to convert a string from Java to Javascript


I'm using Play Framework and I have a .java Controller file in which I obtain an array of strings. I want to pass this Java array into an html file that will use Javascript in order to plot the data using Flot Charts. This data "transfer" is done in the render. It is something like this:

String[] array = new String[list.size()];
int i = 0;
for (Sample sample : list) {
    array[i++] = sample.getContent();
}
render(array);

But then when I'm unable to call this variable in the .html file inside the views folder. If I use ${array}, Firebug tells me that it does not recognize it as a valid JS String array. I've read that Rhino or Nashorn could do the trick, but I do not know if they are the best and simplest option. Any ideas? Thanks!


Solution

  • I'm not familiar with Play Framework but I'm doing similar stuff using SparkJava in both java and javascript (using Nashorn).

    I would suggest to use Boon library to generate json: https://github.com/boonproject/boon.

    Here's a small Nashorn snippet to get you up to speed, easily adaptable to java:

    // 1st we create a factory to serialize json out
    var jso = new org.boon.json.JsonSerializerFactory().create();
    // 2nd we directly use boon on array variable. Boon supports out of the box many pure java objects
    jso.serialize(o);
    

    In your specific case, you'll need to configure Play output for that particular render as application/json and possibly use render(jso.serialize(o)); in place of the small snippet I gave.