I am using Rhino to communicate between Java and JavaScript. I call a JavaScri开发者_运维技巧pt function via Rhino and this function takes an argument which must be a JSON-object. How do i parse Java-object to JSON and pass it to JavaScript in my case? Java-code:
try {
engine.eval(fileReader);
Invocable invocableEngine = (Invocable) engine;
Object o = invocableEngine.invokeFunction("f", MyObject json);
System.out.println(o);
} catch (ScriptException ex) {
ex.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
JavaScript-Code:
function f(json){
var id = json.id;
return id;
}
I haven't used rhino, but for conversion of Java objects/collections to json I use the google library gson.
Back when I was using Rhino I just converted my Java-JSON-Object(org.json.JSONObject) to String and passed them as function parameter to a javascript function existing in the rhino scope.
String itemDatagram = jsonItemDatagram.toString;
String code = "inside.js.scope.aFunction(" + itemDatagram + ");";
The code String object would then have to be evaluated by Rhino. The String object automagically becomes a Javascript object inside the js scope(on the Rhino side). And since JSON is just a subset of javascript objects this should be what you want.
精彩评论