我试图使用 jdk 1.6 中的 ScriptEngine 将表示 JSON 字符串的 String 对象从 java 传递给 javascript 函数。
我的代码在 JSFIDDLE http://jsfiddle.net/hn4yk/13/中工作,但是当我尝试使用 ScriptEngine 加载它时它不起作用并抛出异常 sun.org.mozilla.javascript.internal.EcmaError: TypeError:无法从 undefined 读取属性“resultList” (#1164)
我测试了变量是否正确传递,但 eval 或 JSON.parse 方法不起作用!我试图将 JSON.parse 的库和我的函数放在同一个文件中!
这是我的java代码:
public class InvokeScriptMethod {
public static void main(String[] args) throws Exception {
InputStream stream = new FileInputStream("C:/Subclipse/TestJavascriptServerSide/jsonInput.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer, "UTF-8");
String jsonString = writer.toString();
InputStream javascriptStream = new FileInputStream("C:/Subclipse/TestJavascriptServerSide/Script");
StringWriter writerScript = new StringWriter();
IOUtils.copy(javascriptStream, writerScript, "UTF-8");
String javascriptString = writerScript.toString();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
engine.eval(javascriptString);
Invocable inv = (Invocable) engine;
String convertedJson = (String)inv.invokeFunction("convertJSON",jsonString);
System.out.println("results"+convertedJson);
// now should I convert it to a writer to reply in a webapplication as response.getWriter().print(convertedJson);
// and I would like to don't lose the JSON formatting to see data with indentation
}
}
任何帮助表示赞赏!谢谢!