2012-04-23 19 views
6

¿Existe alguna manera más clara de obtener la representación JSON de un objeto Javascript que con el siguiente kludge?Acceda al JSON.Stringify nativo de Rhino desde Java

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

Donde jsObject es ScriptableObject Quiero stringify.

Respuesta

11

Tenga en cuenta que Hannes tiene now addressed esto en Rhino. Por lo que el uso se simplifica a esto:

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

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

clase El org.mozilla.javascript.NativeJSON debe ser pública en el comunicado de Rhino 1.7R4.

+0

Hola Podría vamos a echar un vistazo a esto: http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent -json? –

+1

Me gustaría utilizar lo anterior, pero no puedo entender cómo obtener el alcance desde la etiqueta Ant/Rhino/Script. El contexto parece accesible a través de .getCurrentContext(), pero no está seguro sobre el alcance. – Joel

0

Pude hacerlo funcionar dentro de un objetivo Apache Ant utilizando la clase 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

Cuestiones relacionadas