Effective way to pass JSON between java and javascript

南笙酒味 提交于 2019-12-04 12:30:20

问题


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 !


回答1:


Nashorn treats java.util.Map objects specially. Nashorn allows Map keys to be treated as "properties". See also https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-SpecialtreatmentofobjectsofspecificJavaclasses

So if your map contains "foo" as key, script can access mapObj.foo to get it's value. It does not matter the script you evaluated is third-party one. As long as the script is evaluated by Nashorn, nashorn will specially link Map property access and get the result you want. This approach avoid unnecessary JSON string conversion and parse round trip (as you yourself mentioned).



来源:https://stackoverflow.com/questions/31292201/effective-way-to-pass-json-between-java-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!