how to get JSON string by using JsonpRequestBuilder
I am usi开发者_JAVA技巧ng GWT's JsonpRequestBuilder to issue a cross site REST request whose response is a JSON object.
The callback parameter of requestObject method is a JavaScriptObject. but I do not want to implement a JavaScriptObject, but rather to parse the JSON response directly. Is there anyway I can get the JSON string directly from any method of JavaScriptObject or JsonpRequestBuilder ?
If you want to use the com.google.gwt.json.JSON
module (seriously, you'd better write JavaScriptObject
s, this JSON module is a PITA to work with), then you can simply wrap the returned JavaScriptObject
into a JSONObject
or JSONArray
:
new JSONObject(myJavaScriptObject)
Use requestString instead of requestObject. Like this:
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.requestString(url,
new AsyncCallback<String>() { ...
This will return a String instead of a JavaScriptObject. You can use then use the JSONParser, like this:
JSONObject value = (JSONObject)JSONParser.parseStrict(jsonString);
Person person = new Person();
person.setName(value.get("Name").isString().stringValue());
@Gu Try to escape quotes in a generated json. For instance in server-side code put
json = json.replace( "\"", "\\\"" )
Than wrap resulting string 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 in client-side:
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.setCallbackParam("jsonpcallback");
jsonp.requestString(....);
P.S. Sorry. Not enough points just to comment already given answer.
精彩评论