ScriptEngine如何传递代表JSON的String?

时间:2013-07-09 12:47:36

标签: json rhino

我试图在jdk 1.6中使用ScriptEngine将一个表示JSON字符串的String对象传递给javascript函数。

我的代码在JSFIDDLE http://jsfiddle.net/hn4yk/13/中工作但是当我尝试使用ScriptEngine加载它时它不起作用并抛出异常sun.org.mozilla.javascript.internal.EcmaError:TypeError:无法读取属性“ resultList“来自undefined(#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
    }
}

任何帮助表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:0)

问题出现在jsonInput文件中我必须将所有Json Stream放在一行中它才有效!