nashorn - Effective way to pass JSON between java and javascript -


i'm new nashorn , scripting on top of jvm , wanted know if can java code , javascripts communicate more effectively.

i'm using 3rd party js lib works js objects, , in java code have data want pass map<string, object> data.

because 3rd party js expects work plain js objects can't pass data is, although script engine allows access map if plain js object.

the script i'm using uses 'hasownproperty' on data argument , fails when invoked on java object.

when tried using object.prototype.hasownproperty.call(data, 'myprop') didn't work , returned 'false'. basic problem java object not javascript object prototype.

what ended doing :

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 expected, json parsing , forth heavy , feels there might simpler, faster , more straight forward way it.

so, there better way pass json between java , javascript or way create compatible js object in java code ?

i've seen this guide template rendering using mustache.js it's doing pretty same thing.

thanks !

nashorn treats java.util.map objects specially. nashorn allows map keys treated "properties". see https://wiki.openjdk.java.net/display/nashorn/nashorn+extensions#nashornextensions-specialtreatmentofobjectsofspecificjavaclasses

so if map contains "foo" key, script can access mapobj.foo it's value. not matter script evaluated third-party one. long script evaluated nashorn, nashorn specially link map property access , result want. approach avoid unnecessary json string conversion , parse round trip (as mentioned).


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -