How to get JSON string using JsonpRequestBuilder

I am using the GWT JsonpRequestBuilder to issue a cross site REST request whose response is a JSON object.

The requestObject method callback parameter is JavaScriptObject. but I don’t want to implement JavaScriptObject, but just parse the JSON response directly. Is there anyway I can get the JSON string directly from any JavaScriptObject or JsonpRequestBuilder method?

+4
source share
3 answers

If you want to use the com.google.gwt.json.JSON module (seriously, it’s better to write JavaScriptObject s, this JSON module is PITA for work), then you can simply wrap the returned JavaScriptObject in a JSONObject or JSONArray :

 new JSONObject(myJavaScriptObject) 
+6
source

Use requestString instead of requestObject. Like this:

 JsonpRequestBuilder jsonp = new JsonpRequestBuilder(); jsonp.requestString(url, new AsyncCallback<String>() { ... 

This will return a string instead of JavaScriptObject. Then you can use JSONParser, for example:

 JSONObject value = (JSONObject)JSONParser.parseStrict(jsonString); Person person = new Person(); person.setName(value.get("Name").isString().stringValue()); 
+1
source

@Gu Try to avoid quotes in generated json. For example, in server code, enter

  json = json.replace( "\"", "\\\"" ) 

Complete the resulting line as follows:

  String jsonCallback = request.getParameter("jsonpcallback") //or any other name StringBuilder response = new StringBuilder(); responseBody.append( jsonCallback ).append( "(\"" ).append( json ).append( "\");"); 

This code works for me on the client side:

  JsonpRequestBuilder jsonp = new JsonpRequestBuilder(); jsonp.setCallbackParam("jsonpcallback"); jsonp.requestString(....); 

PS I'm sorry. Not enough points to just comment on a given answer.

+1
source

All Articles