简体   繁体   English

将JSON数据从JavaScript传递到Java

[英]Passing json data from javascript to Java

I'm trying to pass json data from javascript to java, like below. 我正在尝试将json数据从JavaScript传递到Java,如下所示。 The idea is to pass the data to the java code as a javascript object (and not aa string which I know can be done ). 想法是将数据作为javascript对象传递给Java代码(而不是我知道可以做到的字符串)。 I've tried the code below without success - idea was to use NativeJson.stringify to convert from a javascript object to a Java string, however this results in an Undefined instance instead of the expected string. 我尝试了下面的代码,但没有成功-想法是使用NativeJson.stringify从javascript对象转换为Java字符串,但是这会导致未定义的实例,而不是预期的字符串。 Any idea on this could be achieved much appreciated. 任何对此的想法都可以实现。

in javascript file "test.js" 在javascript文件“ test.js”中

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

in java 在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

}

Could not find a way to use NativeJSON.stringify(). 找不到使用NativeJSON.stringify()的方法。 I ended up building the json string "by hand", ie Iterating on the property ids of the native javascript object and adding these properties to a java Map. 我最终“手动”构建了json字符串,即迭代本机javascript对象的属性ID,并将这些属性添加到Java Map中。

The Map is then transformed into a json object using new JSONObject(map); 然后使用新的JSONObject(map)将Map转换为json对象;

link to source code https://gist.github.com/eleco/c2bc77dca9ecc844a924 链接到源代码https://gist.github.com/eleco/c2bc77dca9ecc844a924

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

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