ScriptEngine how to pass a string representing JSON?

I tried to pass a String object representing a JSON string from java to javascript using ScriptEngine in jdk 1.6.

My code works in JSFIDDLE http://jsfiddle.net/hn4yk/13/ , but when I try to load it using ScriptEngine, it does not work and throws an exception .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 JSON.parse method does not work! I tried to put the library for JSON.parse and my function in one 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! Thanks!

0
json rhino
source share
1 answer

The problem was in the jsonInput file, which I had to put the entire Json Stream on one line, and it works!

0
source share

All Articles