I'm fairly new to Nashorn and scripting on top of the JVM and wanted to know if I can get my java code and javascripts to communicate more effectively.
I'm using a 3rd party JS lib that works with JS objects, and in my java code I have the data I want to pass as a Map<String, Object> data
.
Because that 3rd party JS expects to work with plain JS objects I can't pass my data
as is, although the script engine allows you to access a Map as if it was a plain JS object.
The script i'm using uses 'hasOwnProperty' on the data argument and fails when invoked on an Java object.
When I tried using Object.prototype.hasOwnProperty.call(data, 'myProp') it also didn't work and always returned 'false'. The basic problem is that a Java Object is not a javascript object prototype.
what I ended up doing something like this :
Map<String, Object> data;
ObjectMapper mapper = new ObjectMapper();
String rawJSON = mapper.writeValueAsString(data);
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval('third_party_lib.js');
engine.eval('function doSomething(jsonStr) { var jsObj = JSON.parse(jsonStr); return doSomethingElse(jsObj); }');
Object value = ((Invocable) engine).invokeFunction("doSomething", rawJSON);
This works as expected, but all this JSON parsing back and forth is heavy and feels like there might be simpler, faster and more straight forward way to do it.
So, is there a better way to pass JSON between Java and Javascript or a way to create a compatible JS object in my Java code ?
I've seen this guide to template rendering using mustache.js but it's doing pretty much the same thing.
Thanks !