Access Rhino's native JSON.Stringify from Java
Asked Answered
M

2

8

Is there a cleaner way to get the JSON representation of a Javascript object than with the following kludge?

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

Where jsObject is the ScriptableObject I want to stringify.

Muslin answered 23/4, 2012 at 21:35 Comment(0)
C
12

Note that Hannes has now addressed this in Rhino. So the usage simplifies to this:

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

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

The org.mozilla.javascript.NativeJSON class should be public in the Rhino 1.7R4 release.

Crossstaff answered 31/5, 2012 at 16:13 Comment(1)
I'd like to use the above, but I can't figure out how to get the scope from within Ant/Rhino/Script tag. Context seems accessible thru .getCurrentContext(), but not sure about scope.Builtin
L
1

I was able to get this working within an Apache Ant target using the NativeJSON class.

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

Lath answered 27/9, 2017 at 22:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.