Java 对象到 JSON

发布于 2024-10-02 08:50:24 字数 579 浏览 8 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦魇绽荼蘼 2024-10-09 08:50:24

我没有使用过 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.

肥爪爪 2024-10-09 08:50:24

当我使用 Rhino 时,我只是将 Java-JSON-Object(org.json.JSONObject) 转换为 String 并将它们作为函数参数传递给 rhino 范围中存在的 javascript 函数。

String itemDatagram = jsonItemDatagram.toString; 
String code = "inside.js.scope.aFunction(" + itemDatagram + ");";

然后,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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文