8

次のクラッジを使用するよりも、JavascriptオブジェクトのJSON表現を取得するためのよりクリーンな方法はありますか?

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

ここで、jsObjectは文字列化するScriptableObjectです。

4

2 に答える 2

12

Hannes は現在、Rhino でこれに対処していることに注意してください。したがって、使用法は次のように単純化されます。

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

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

org.mozilla.javascript.NativeJSON クラスは、Rhino 1.7R4 リリースで公開する必要があります。

于 2012-05-31T16:13:24.907 に答える
1

NativeJSON クラスを使用して、Apache Ant ターゲット内でこれを機能させることができました。

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

于 2017-09-27T22:52:22.147 に答える