Converting a Javascript array to a Java array

一世执手 提交于 2019-12-01 21:27:11
maerics

Per this answer it looks like your best bet is to write a JavaScript converter function which transforms the native JavaScript array into a Java array using Rhino's Java binding functionality. Note that you'll have to take some care to use the correct type when converting the individual elements.

[Edit] Here's a working example using a string array:

ScriptEngine js = new ScriptEngineManager().getEngineByName("JavaScript");
String ss[] = (String[]) js.eval(
    "(function() {" +
    "  var a = java.lang.reflect.Array.newInstance(java.lang.String, 3);" +
    "  a[0] = 'foo';" +
    "  a[1] = 'bar';" +
    "  a[2] = 'gah';" +
    "  return a;" +
    "})()");
System.out.println(Arrays.toString(ss)); // => [foo, bar, gah]
chubbsondubs

Rhino offers this:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Embedding_tutorial#usingJSObjs

Also Scriptable interface offers get() and set() so you can easily enumerate the properties of an object and add it to an array:

Scriptable arr = (Scriptable) result;
Object [] array = new Object[arr.getIds().length];
for (Object o : arr.getIds()) {
   int index = (Integer) o;
   array[index] = arr.get(index, null);
}

Same thing but not using NativeArray since that appears to be a Rhino specific thing. You could easily drop a breakpoint and see what type of object you were given then downcast to that. It's some sort of JS Array implementation that's pretty close to NativeArray.

I would recommend Doug Crockfords JSON-java library. This allows you to convert json to native JAVA objects.

Artemiy

I would simply use json-lib and parse the array that way. for example see How to parse a JSON and turn its values into an Array?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!