2012-04-23 20 views
6

Bir Javascript nesnesinin JSON temsilini aşağıdaki klozayla karşılaştırmak için daha temiz bir yol var mı?Erişim Rhino'nun yerel JSON.Stringify - Java

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

jsObject, ScriptableObject öğesidir.

cevap

11

Hannes'in Rhino'da now addressed olduğunu unutmayın. Yani kullanım Buna kolaylaştırır:

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

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

org.mozilla.javascript.NativeJSON sınıfı Rhino 1.7R4 sürümdeki herkese açık olmalıdır.

+0

Merhaba size en bu konuda bir bakalım Could: http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent -json? –

+1

Yukarıdakileri kullanmak istiyorum, ancak kapsamı Ant/Rhino/Script etiketinin içinden nasıl alacağımı anlayamıyorum. Bağlam, .getCurrentContext() aracılığıyla erişilebilir görünüyor, ancak kapsam hakkında emin değilim. – Joel

0

Bu uygulamayı NativeJSON sınıfını kullanarak bir Apache Ant hedefi içinde çalıştırabildim.

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

İlgili konular