nprokofiev
nprokofiev

Reputation: 51

GWT native to long conversion

I'm trying to convert js native number to GWT Long and send it over gwt-rpc. But I got very weird results..

public class gwtbugEntryPoint implements EntryPoint {
  @Override
  public void onModuleLoad() {
    String data = "{\"type\":\"upd\", \"id\":123}";
    ServerEvent serverEvent = JsonUtils.<ServerEvent>safeEval(data);
    RootPanel.get().add(new HTML("GWT id="+serverEvent.getId()));
  }

}
class ServerEvent extends JavaScriptObject {
    protected ServerEvent() {
    }

public final native String getType()/*-{ return this.type; }-*/;

public final Long getId(){
    String idStr = _getId();
    GWT.log("idSTr:" + idStr);
    Long id = new Long(idStr);
    GWT.log("id:"+id);
    return id;
}

public final native String  _getId()/*-{ return this.id; }-*/;
}

console output:

idSTr:123

id:0

Can anyone explain me, how that could happen?

Upvotes: 2

Views: 454

Answers (3)

Adam
Adam

Reputation: 5599

You should not use long with JavaScript as it is explained here: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#important

Basically, the simplest way is to use double.

Upvotes: 1

nprokofiev
nprokofiev

Reputation: 51

The problem was in converting js native numeric to long. The best option to avoid converting js numbers to long or use strings.

Here is the fix for this case:

public final native String  _getId()/*-{ return ''+this.id; }-*/;

Upvotes: 1

alexp
alexp

Reputation: 797

No info here on the JavaScriptObject you are using. Did you mean https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number ?

What is that 'id' field you are querying?

Quick test in Chrome console shows me that you would want to use the following to get Number's value as string:

var d = new Number(100)
> undefined
d.toString()
> "100"

If you are using a different kind of js "native" number, please provide more details.

Upvotes: 0

Related Questions