2012-04-23 93 views
6

是否有一个更清晰的方式来获取JavaScript对象的JSON表示比下面的kludge?访问犀牛的原生JSON.Stringify从Java

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

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

回答

11

请注意,汉尼斯有这个在犀牛now addressed。所以使用简化为这样:

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

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

的org.mozilla.javascript.NativeJSON类应该是公共的犀牛1.7R4版本。

+0

你好你能不能让我们对这个一看:http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent -json? – 2013-07-09 13:53:32

+1

我想使用上述内容,但我无法弄清楚如何从Ant/Rhino/Script标签中获取范围。 Context似乎可以通过.getCurrentContext()访问,但不能确定范围。 – Joel 2013-08-30 16:12:13

0

我能够使用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