8

有没有比使用以下 kludge 更简洁的方法来获取 Javascript 对象的 JSON 表示?

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

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

4

2 回答 2

12

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

import org.mozilla.javascript.NativeJSON;
// ...

Object json = NativeJSON.stringify(cx, scope, jsObject, null, null);

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

于 2012-05-31T16:13:24.907 回答
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

于 2017-09-27T22:52:22.147 回答