2012-04-23 3 views
6

다음 kludge보다 Javascript 객체의 JSON 표현을 가져 오는 더 깨끗한 방법이 있습니까?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 클래스는 코뿔소 1.7R4 릴리스에 공개한다.

+0

안녕하세요 당신의이에 살펴보기로하자 수 : http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent - 슨? –

+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