2012-04-23 2 views
6

Esiste un modo più semplice per ottenere la rappresentazione JSON di un oggetto Javascript rispetto al seguente kludge?Accesso a JSON nativo di Rhino. Modifica da Java

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

Dove jsObject è ScriptableObject voglio stringificare.

risposta

11

Si noti che Hannes ha now addressed questo in Rhino. Quindi l'utilizzo semplifica a questo:

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

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

classe L'org.mozilla.javascript.NativeJSON dovrebbe essere pubblico nel rilascio di Rhino 1.7R4.

+0

Ciao Potrebbe diamo un'occhiata a questo: http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent -json? –

+1

Mi piacerebbe usare quanto sopra, ma non riesco a capire come ottenere l'ambito dal tag Ant/Rhino/Script. Il contesto sembra accessibile attraverso .getCurrentContext(), ma non è sicuro dell'ambito. – Joel

0

Sono riuscito a farlo funzionare all'interno di un target di Ant Apache utilizzando la classe NativeJSON.

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