Efficient way to pass JSON between java and javascript

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!

+7
java scriptengine nashorn
source share
1 answer

Nashorn processes java.util.Map objects on purpose. Nashorn allows you to use map keys as "properties." See Also https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-SpecialtreatmentofobjectsofspecificJavaclasses

So, if your map contains "foo" as a key, the script can access mapObj.foo to get its value. It doesn't matter that you rated the third-party script. While the script is being evaluated by Nashorn, nashorn will specifically associate access to the map properties and get the desired result. This approach avoids unnecessary JSON string conversion and round-trip parsing (as you yourself mentioned).

+5
source share

All Articles