简体   繁体   English

如何使用 Rihno (Java) 将解析的 JSON 传递给 JavaScript 函数?

[英]How to pass parsed JSON to a JavaScript function with Rihno (Java)?

I am using Rhino to invoke a JavaScript makeQuery(hints) function in Java.我正在使用 Rhino 在 Java 中调用 JavaScript makeQuery(hints)函数。

I have a String that contains JSON and I want to pass it as parameter to a JavaScript function.我有一个包含 JSON 的字符串,我想将它作为参数传递给 JavaScript 函数。 The way I am currently doing is that I pass the string and then parse it in the JavaScript function.我目前的做法是传递字符串,然后在 JavaScript 函数中解析它。 However, I don't want to have to parse it in the function ie I want it already parsed.但是,我不想在函数中解析它,即我希望它已经被解析过。

Here is my code handling calling the JavaScript function:这是我处理调用 JavaScript 函数的代码:

Context context = Context.enter();
try {
    // rawJSON is the string that contains the JSON. hints is the parsed JSON I want.
    var hints = Context.javaToJS(rawJSON, context.initStandardObjects());

    ScriptableObject scope = context.initStandardObjects();
    // script is a string containing the code of the JavaScript function.
    context.evaluateString(scope, script, "script", 1, null);
    Function makeQuery = (Function) scope.get("makeQuery", scope);

    // hints here is passed as a String, but I want it passed as a native JSON
    Object result = makeQuery.call(context, scope, scope, new Object[]{hints});
    return (String) Context.jsToJava(result, String.class);
} finally {
    Context.exit();
}

And here is the JavaScript function:这是 JavaScript 函数:

function makeQuery(rawHints) {
    // I don't want to have to do this. I want it to arrive already parsed.
    const hints = JSON.parse(rawHints);
    return `From the hints below, generate a 1500 to 3000 words article.\n
Hints:
Title: ${hints.title}
Description: ${hints.description}
Tags: ${hints.tags.join(",")}\\n
    `
}

What I tried我试过的

I tried to parse hints to a NativeObject but it returns the exception that it can't convert NativeJavaObject to NativeObject .我试图将hints解析为NativeObject但它返回无法将NativeJavaObject转换为NativeObject的异常。

The solution is to use the NativeJSON.parse method.解决方案是使用NativeJSON.parse方法。 This is how I did it:我就是这样做的:

var hints = NativeJSON.parse(context, scope, rawJSON, (context1, scriptable, scriptable1, objects) -> objects[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM