2010-11-10 87 views
2

我正在使用Rhino在Java和JavaScript之间进行通信。 我通过Rhino调用一个JavaScript函数,这个函数接受一个必须是JSON对象的参数。如何解析Java对象到JSON并将其传递给JavaScript在我的情况? 的Java代码:Java对象到JSON

try {  
    engine.eval(fileReader); 
    Invocable invocableEngine = (Invocable) engine; 
    Object o = invocableEngine.invokeFunction("f", MyObject json); 
    System.out.println(o); 
} catch (ScriptException ex) { 
    ex.printStackTrace(); 
} catch(Exception e){ 
    e.printStackTrace(); 
} 

的JavaScript代码:

function f(json){ 
    var id = json.id; 
    return id; 
} 

回答

4

我没有用犀牛,但对于Java对象的转换/收藏到JSON我使用谷歌图书馆gson

2

当我使用Rhino时,我刚刚将Java-JSON-Object(org.json.JSONObject)转换为String,并将它们作为函数参数传递给存在于rhino范围内的javascript函数。

String itemDatagram = jsonItemDatagram.toString; 
String code = "inside.js.scope.aFunction(" + itemDatagram + ");"; 

然后代码字符串对象必须由Rhino评估。 String对象自动成为js范围内的一个Javascript对象(在Rhino方面)。由于JSON只是javascript对象的一个​​子集,所以这应该是你想要的。

+0

您好!你能让我们看看这个:http://stackoverflow.com/questions/17548552/scriptengine-how-to-pass-a-string-that-represent-json?你能告诉我你的方法是如何工作的吗? – 2013-07-09 13:03:22