访问犀牛的原生 JSON。从 Java 字符串化



有没有比以下方法更干净的方法来获取Javascript对象的JSON表示?

System.out.println(((ScriptableObject) scope).callMethod(
    cx, (Scriptable) scope.get("JSON", scope), 
    "stringify", new Object[]{jsObject}));

其中jsObject是我想要字符串化的ScriptableObject。

请注意,Hannes 现在已经在 Rhino 中解决了这个问题。 因此,用法简化为:

import org.mozilla.javascript.NativeJSON;
// ...
Object json = NativeJSON.stringify(cx, scope, jsObject, null, null);

org.mozilla.javascript.NativeJSON 类应该在 Rhino 1.7R4 版本中是公开的。

我能够使用NativeJSON类在Apache Ant目标中使其工作。

importPackage(org.mozilla.javascript);
var context = Context.enter();
var json = '{}';
// The call to parse required a reviver function that should return the
// state of a key/value pair.
var reviver = function(key, value) { return value; };
var scope = context.initStandardObjects();
var object = NativeJSON.parse(context, scope, json, reviver);
// The call to stringify does not require the replacer or space parameters.
// The replacer is a function that takes a key/value pair and returns the
// new value or an array of keys from the input JSON to stringify. The space
// parameter is the indentation characters or length.
json = NativeJSON.stringify(context, scope, config, null, 4);

http://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/NativeJSON.htmlhttps://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeJSON.java

最新更新