Java 对象到 JSON
我正在使用 Rhino 在 Java 和 JavaScript 之间进行通信。 我通过 Rhino 调用 JavaScript 函数,该函数接受一个参数,该参数必须是 JSON 对象。在我的例子中,如何将 Java 对象解析为 JSON 并将其传递给 JavaScript? Java 代码:
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 代码:
function f(json){
var id = json.id;
return id;
}
I am using Rhino to communicate between Java and JavaScript.
I call a JavaScript 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有使用过 rhino,但是为了将 Java 对象/集合转换为 json,我使用了 google 库 gson。
I haven't used rhino, but for conversion of Java objects/collections to json I use the google library gson.
当我使用 Rhino 时,我只是将 Java-JSON-Object(org.json.JSONObject) 转换为 String 并将它们作为函数参数传递给 rhino 范围中存在的 javascript 函数。
然后,Rhino 必须评估代码 String 对象。 String 对象自动成为 js 范围内的 Javascript 对象(在 Rhino 端)。由于 JSON 只是 javascript 对象的子集,这应该就是您想要的。
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.
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.