Access Rhino's native JSON.Stringify from Java

南楼画角 提交于 2019-11-29 04:32:33

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!