ScriptEngine如何传递表示JSON的字符串? [英] ScriptEngine how to pass a String that represent JSON?
问题描述
我试图使用jdk 1.6中的ScriptEngine将代表JSON字符串的字符串对象从Java传递到javascript函数.
I was trying to pass a String object that represents a JSON string from java to javascript function using ScriptEngine in jdk 1.6.
我的代码在JSFIDDLE中运行 http://jsfiddle.net/hn4yk/13/我尝试使用无法正常工作的ScriptEngine加载它,并抛出异常sun.org.mozilla.javascript.internal.EcmaError:TypeError:无法从未定义的属性中读取"resultList"(#1164)
My code works in JSFIDDLE http://jsfiddle.net/hn4yk/13/ but when I try to load it with the ScriptEngine it doesn't work and throws an exception sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot read property "resultList" from undefined (#1164)
我测试了变量是否正确传递,但是eval或JSON.parse方法不起作用!我试图将JSON.parse库和我的函数放在同一个文件中!
I tested that the variable is passed correctly but the eval or the JSON.parse method doesn't work! I tried to put the library for JSON.parse and my function in the same file!
这是我的Java代码:
This is my java code:
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
}
}
感谢您的帮助!谢谢!
推荐答案
问题出在jsonInput文件上,我不得不将所有Json Stream放在一行中并且可以正常工作!
The problem was on the jsonInput file I had to put all Json Stream in a single line and it works!
这篇关于ScriptEngine如何传递表示JSON的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!