2012-04-23 8 views
6

JavascriptオブジェクトのJSON表現を次のkludgeで取得するよりクリーンな方法がありますか?RhinoのネイティブJSON.Stringify Javaへのアクセス

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

ここで、jsObjectは文字列化したいScriptableObjectです。

答えて

11

HannesはRhinoでnow addressedです。だから、使用法は、このように簡略化:

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

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

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

+0

こんにちはあなたはのは、この上を見てみましょうでした:http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent -json? –

+1

上記を使用したいと思いますが、Ant/Rhino/Scriptタグ内からスコープを取得する方法を理解できません。コンテキストは.getCurrentContext()を介してアクセス可能なようですが、スコープについては不明です。 – Joel

0

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

関連する問題