Search code examples
jsongwtiterationjsni

Iterating over JSONObject in GWT JSNI


I have a native method which should iterate over the JSONObject. Is there a way to achieve this?

public native void foo(JSONObject c)/*-{
    var keys = [email protected]::keySet()();

    for ( var k : keys ){
        alert(k); // this does not fire up. no error in console :(
    }
}-*/;

Also, is there a way convert Java Map type to JSONObject?

Any hint would be much appreciated! Thanks! :)


Solution

  • JSONObject#keySet returns a Set, which is an object wrapping a JS array (in prod mode; in DevMode it's the standard java.util.Set from your JVM.

    So, either use plain Java:

    Set<String> keys = c.keySet();
    for (String key : keys) {
      Window.alert(key); // or call a JSNI method here if you need?
    }
    

    or first extract the underlying JavaScriptObject and then you can use a JS for…in:

    var o = [email protected]::getJavaScriptObject()();
    for (var k in o) {
      if (o.hasOwnProperty(k)) {
        alert(k);
      }
    }