Jovan Perovic
Jovan Perovic

Reputation: 20201

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! :)

Upvotes: 2

Views: 1513

Answers (2)

Thomas Broyer
Thomas Broyer

Reputation: 64551

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);
  }
}

Upvotes: 3

apanizo
apanizo

Reputation: 628

Have you tried something like:

for (var k in c) {
  if (c.hasOwnProperty(k)) {
    alert(k+":"+c[k]);
  }
}

I my memory does not fail, I think this code works...

About your second question, if your entity is a Java-GWT valid entity, you can use Autobeans for getting the JsonObject.

Upvotes: 2

Related Questions