繁体   English   中英

将JSON数据从JavaScript传递到Java

[英]Passing json data from javascript to Java

我正在尝试将json数据从JavaScript传递到Java,如下所示。 想法是将数据作为javascript对象传递给Java代码(而不是我知道可以做到的字符串)。 我尝试了下面的代码,但没有成功-想法是使用NativeJson.stringify从javascript对象转换为Java字符串,但是这会导致未定义的实例,而不是预期的字符串。 任何对此的想法都可以实现。

在javascript文件“ test.js”中

parser.fct ( {"abc":123,"def":456} )

在java中

//1.binds javascript calls to Java
...
ScriptEngine engine = new ScriptEngine...
Bindings bindings = engine.createBindings();
bindings.put("parser", new Parser());
engine.eval("test.js");

//2. in Parser class
public void fct(Object obj){
   Context ctx = Context.enter();
   ScriptableObject scope = ctx.initStandardObjects();
   Object json = NativeJSON.stringify(ctx, scope, obj, null,null);

   //json returned is of type Undefined

}

找不到使用NativeJSON.stringify()的方法。 我最终“手动”构建了json字符串,即迭代本机javascript对象的属性ID,并将这些属性添加到Java Map中。

然后使用新的JSONObject(map)将Map转换为json对象;

链接到源代码https://gist.github.com/eleco/c2bc77dca9ecc844a924

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM