I'm looking for the best way in GWT to access a 3party json rest service and parse its response quickly. The rest service offers the callback
parameter, and the example they gave us is using jQuery.jsonp:
$.ajax({
type: 'GET',
url: 'http://server_name?id=and_id&callback=?',
contentType: "application/json",
dataType: 'jsonp',
success: function(js) {/*{id='id',status='sold',prod_name='name',price=0.0 ...}*/},
error: function(e) {}
});
Although GWT comes with a JsonpRequestBuilder to perform requests via script tags and AutoBeans to handle json responses and generate java implementations, I prefer gwtquery Ajax and DataBinding because of its simplicity.
In your case you could have almost the same syntax that your provider gave you:
ajax("http://server_name?id=and_id&callback=?",
$$("type:'get', dataType: 'jsonp'),
new Function() {
public void f() {
Properties jso = getDataProperties();
String status = jso.get("error");
}
});
If you prefer to use builders because you like get/setters your code could look like this:
public static interface MResponse extends JsonBuilder {
String getId();
String getStatus();
String getProd_name();
double getPrice();
}
ajax(Ajax.createSettings()
.setType("get")
.setDataType("jsonp")
.setUrl(""))
.done(new Function() {
public void f() {
MResponse resp = GWT.<MResponse>create(MResponse.class)
.load(getDataProperties());
String status = resp.getStatus();
}
});