javascript – 使用Rhino和JSR-223读取JSON文件

我正在尝试使用一些JavaScript来读取JSON文件,我正在通过Java JSR-223 API与Rhino一起评估.我正在尝试使用Rhino shell,但不能使用我的Java代码中的嵌入式Javascript.

这是有效的:

$java -jar js.jar
js> readFile('foo.json');
{y:"abc"}

这是不起作用的:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("js");
engine.eval("readFile('foo.json')"); 

我收到此错误:

Exception in thread "main" javax.script.ScriptException: 
sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "readFile" is not defined. (<Unknown source>#4) in <Unknown source> at line number 4
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:153)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:232)

如何让readFile在我的引擎中可用?

解决方法:

如果您只是想解析JSON,我建议使用JSON解析库,如JacksonJettison,这是一个更容易的方法. readFile调用返回一个字符串,它实际上并没有将内容转换为JavaScript对象.为了实现这一点,需要对字符串进行JSON.parse or JavaScript eval调用.

如果你真的需要使用JavaScript引擎解析JSON而你使用的是Java 7,你可以做这样的事情(但我不建议)……

public static void main(final String args[]) throws Exception {
    final ScriptEngineManager factory = new ScriptEngineManager();
    final ScriptEngine engine = factory.getEngineByName("js");
    Object val = null;
    Scanner s = null;
    try {
        s = new Scanner(new File("foo.json"));
        s.useDelimiter("\\Z");
        engine.getBindings(ScriptContext.GLOBAL_SCOPE).put("json", s.next());
    } finally {
        if (s != null) {
            s.close();
        }
    }
    // The default JavaScript engine in Java 6 does not have JSON.parse
    // but eval('(' + json + ')') would work
    val = engine.eval("JSON.parse(json)");

    // The default value is probably a JavaScript internal object and not very useful
    System.out.println(val.getClass() + " = " + val);
    // Java 7 uses Rhino 1.7R3 the objects will implement Map or List where appropriate
    // So in Java 7 we can turn this into something a little more useable
    // This is where Java 6 breaks down, in Java 6 you would have to use the 
    // sun.org.mozilla.javascript.internal classes to get any useful data
    System.out.println(convert(val));
}

@SuppressWarnings("unchecked")
public static Object convert(final Object val) {
    if (val instanceof Map) {
        final Map<String, Object> result = new HashMap<String, Object>();
        for (final Map.Entry<String, Object> entry: ((Map<String, Object>) val).entrySet()) {
            result.put(entry.getKey(), convert(entry.getValue()));
        }
        return result;
    } else if (val instanceof List) {
        final List<Object> result = new ArrayList<Object>();
        for (final Object item: ((List<Object>) val)) {
            result.add(convert(item));
        }
        return result;
    }
    if (val != null) {
        System.out.println(val.getClass() + " = " + val);
    }
    return val;
}

Java提供的JavaScript引擎具有excluded Rhino中提供的一些功能. readFile函数实际上是由Rhino Shell提供的,而不是引擎实现. Oracle also provides functions可由jrunscript shell访问,它们不在引擎中.

这是一个模仿Rhino shell readFile函数的示例,并根据此问题的答案将其添加到JavaScript范围:
How can I add methods from a Java class as global functions in Javascript using Rhino?

public static void main(final String args[]) throws Exception {
    final ScriptEngineManager factory = new ScriptEngineManager();
    final ScriptEngine engine = factory.getEngineByName("js");
    engine.getBindings(ScriptContext.GLOBAL_SCOPE).put("utils", new Utils());
    engine.eval("for(var fn in utils) {\r\n" +
            "  if(typeof utils[fn] === 'function') {\r\n" +
            "    this[fn] = (function() {\r\n" +
            "       var method = utils[fn];\r\n" +
            "       return function() {\r\n" +
            "         return method.apply(utils,arguments);\r\n" +
            "       };\r\n" +
            "    })();\r\n" +
            "  }\r\n" +
            "}");
    engine.eval("println(readFile('foo.json'))");
}

static class Utils {
    public String readFile(final String fileName) throws FileNotFoundException {
        return readFile(fileName, null);
    }
    public String readFile(final String fileName, final String encoding) throws FileNotFoundException {
        Scanner s = null;
        try {
            s = new Scanner(new File(fileName), (encoding == null)? Charset.defaultCharset().name(): encoding);
            s.useDelimiter("\\Z");
            return s.next();
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
}
上一篇:如何在Java中将.js文件加载到Rhino上下文中


下一篇:java-Htmlunit ScriptException“控制台”未定义