2012-04-23 41 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