Skip to main content

Converting a Javascript array to a Java array



I'm trying to convert a Javascript array in Java to a Java array. I tested this example here, but the type "NativeArray" was not recognized: http://stackoverflow.com/a/1433489/975097





How can I get the NativeArray type to be recognized?


Comments

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

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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?

    ReplyDelete
  4. Rhino offers this:
    http://www.mozilla.org/rhino/tutorial.html#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.

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?