I am new to Nashorn and wrote a script on top of the JVM and wanted to know if I could get a more efficient exchange of java code and javascripts.
I use a third-party JS library that works with JS objects, and in my java code I have data that I want to pass as Map<String, Object> data .
Since this third-party JS expects to work with explicit JS objects, I cannot pass my data as is, although the script engine allows you to access the map as if it were a simple JS object.
script I use 'hasOwnProperty' to use in the data argument and fails when called on a Java object.
When I tried to use Object.prototype.hasOwnProperty.call (data, 'myProp'), it also did not work and always returned false. The main problem is that the Java object is not a prototype of the javascript object.
that 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 of these back-and-forth JSON analyzes are heavy and feel that there may be a simpler, faster, and more direct way to do this.
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 saw this tutorial on rendering templates using mustache.js, but it does almost the same thing.
Thanks!
java scriptengine nashorn
Ronny shapiro
source share