GWT and JSON error in eval – JavaScriptException: (SyntaxError): Unexpected token :

In GWT 2.x you can do a JSON-P request for CORS using JsonpRequestBuilder. That’s is really useful! But if you have a service that don’t support JSON-P or you want to use JSON with Access-Control-Allow-Origin header for CORS you have to use JSNI eval in GWT.

public void getJson(String url, final AsyncCallback asyncCallback) {
  RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
  try {
    builder.sendRequest(null, new RequestCallback() {
    public void onError(Request request, Throwable exception) {
      asyncCallback.onFailure(exception);
    }
    public void onResponseReceived(Request request, Response response) {
      if (200 == response.getStatusCode()) {
        String json = response.getText();
        asyncCallback.onSuccess(evalJson(json));
      } else {
        asyncCallback.onFailure(new Throwable());
      }
    }});
  } catch (RequestException e) {}
}
private final native MyJson evalJson(String json) /*-{
  return eval(json);
}-*/;

throws an exception!

com.google.gwt.core.client.JavaScriptException: (SyntaxError): Unexpected token :
arguments: :
type: unexpected_token
stack: SyntaxError: Unexpected token :
at eval (native)

to solve this issue simply assign a variable to your json string into the eval

private final native MyJson evalJson(String json) /*-{
  eval('var res = ' + json);
  return res;
}-*/;

that’s it 🙂

Posted in GWT

8 thoughts on “GWT and JSON error in eval – JavaScriptException: (SyntaxError): Unexpected token :

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s