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 = c.@com.google.gwt.json.client.JSONObject::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! :)

有帮助吗?

解决方案

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 = c.@com.google.gwt.json.client.JSONObject::getJavaScriptObject()();
for (var k in o) {
  if (o.hasOwnProperty(k)) {
    alert(k);
  }
}

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top