I coded the following to send JSON data to the front end. But due to cross-domain security woes we need to convert it to JSONP, can someone suggest what I need to modify for this conversion?
JsonFactory jfactory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
try {
StringWriter stringWriter = new StringWriter();
JsonGenerator jGenerator = jfactory.createJsonGenerator(stringWriter);
jGenerator.useDefaultPrettyPrinter();
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("title", title); // "title" : title
jGenerator.writeStringField("Description", desc); // "desc" :
jGenerator.writeFieldName("images");
jGenerator.writeStartArray(); // [
if(imageArray.size() != 0){
for (String img : imageArray) {
jGenerator.writeString(img); // "msg 1"
}
}
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
jGenerator.close();
response.getWriter().write(stringWriter.toString());
System.out.println(stringWriter.toString());
response.getWriter().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JasonGen servlet called end");
$.getJSON("http://localhost:8080/JsoupPrj/JasonGen?url="+ url[0],function(data){
var imageArray=[];
var imageOne = null;
imageArray=data.images;
....................
}
Since you're using jQuery and you control the server-side, change your server code so that it looks for the callback
parameter. The value of this parameter will be the name of the callback function that the client-side code is expecting. Then instead of returning the bare JSON, return it in the form: callbackName(rawJson)
.
For instance, assuming a servlet API:
String callbackName = request.getParameter("callback");
// ... your JSON code
if (callbackName != null)
{
// JSONP wrapping:
response.getWriter().write(callbackName +
"(" + stringWriter.toString() + ")");
System.out.println(callbackName + "(" + stringWriter.toString() + ")");
}
else
{
response.getWriter().write(stringWriter.toString());
System.out.println(stringWriter.toString());
}
response.getWriter().close();
Then on the client-side, continue to use jQuery.getJSON
, but append a ?callback=?
query parameter to your URL, or instead use jQuery.ajax
for your call, and use the dataType: jsonp
setting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With