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 🙂


Please remember that eval it’s not a good practice in javascript&GWT because can open to XSS attachs. Check the validity of JSON before call the eval!
Examples here http://www.json.org/js.html
thanks, I’ve been banging my head against this problem all day
ur welcome!
I had exactly this issue (with GWT, JSON and CORS). Thanks for saving my day!
You are welcome!
Thank you so much, you saved my day!
Thanks!
You are welcome 🙂