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

时间:2012-04-12 15:13:55

标签: javascript rhino jsr223

我正在尝试使用一些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在我的引擎中可用?

2 个答案:

答案 0 :(得分:5)

如果您只是想解析JSON,我建议使用像JacksonJettison这样的JSON解析库,这是一种更简单的方法。 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提供,而不是引擎实现。 also provides functions shell可以访问的Oracle jrunscript不在引擎中。

这是一个模仿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();
            }
        }
    }
}

答案 1 :(得分:0)

你总是可以利用相关的Java类来粘贴JSON文件,然后装饰它以使它适合于eval()。

可以在一行中整齐地完成。例如,给出以下内容:

cfg.json:

{     
    myopts: {
        username: "tee",
        password: "password"
    }
}

以下Javascript:

cfg = eval('(' + new java.util.Scanner( new java.io.File('cfg.json') ).useDelimiter("\\A").next() + ')');

您现在可以通过以下方式在Javascript中访问您的JSON:

log.info("Username: " + cfg.myopts.username ); // "Username: tee"