Access Rhino's native JSON.Stringify from Java

ironchefpython picture ironchefpython · Apr 23, 2012 · Viewed 13.1k times · Source

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.

Answer

Tim Schaub picture Tim Schaub · May 31, 2012

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.