The problem was on the jsonInput file I had to put all Json Stream in a single line and it works!
ScriptEngine how to pass a String that represent JSON?
سؤال
I was trying to pass a String object that represents a JSON string from java to javascript function using ScriptEngine in jdk 1.6.
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)
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!
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
}
}
Any help is appreciated! Thank you!
المحلول
لا تنتمي إلى StackOverflow