是否有更简洁的方法来获取Javascript对象的JSON表示而不是以下kludge?
System.out.println(((ScriptableObject) scope).callMethod(
cx, (Scriptable) scope.get("JSON", scope),
"stringify", new Object[]{jsObject}));
其中jsObject是我想要字符串化的ScriptableObject。
答案 0 :(得分:12)
请注意,Hannes在Rhino中有now addressed这个。因此,使用简化为:
import org.mozilla.javascript.NativeJSON;
// ...
Object json = NativeJSON.stringify(cx, scope, jsObject, null, null);
org.mozilla.javascript.NativeJSON类应该在Rhino 1.7R4版本中公开。
答案 1 :(得分:1)
我能够使用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.html https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeJSON.java