Showing posts with label Pjson. Show all posts
Showing posts with label Pjson. Show all posts

Tuesday, June 21, 2011

PJson in Spring using JacksonJson (Cross Domain Issues)

We can create pjson (json with padding) to achieve cross domain java-script call which is very important if data is coming from other domain.

Here is what i did to get pjson from object.
I created a class MappingJacksonJsonpView extended it by AbstractView, now here is the trick
I overrided a method renderMergedOutputModel as follows:

@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception
{
Object value = filterModel(model);
JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), encoding);
String callback = request.getParameter("jsoncallback");
prefixJson = false;
if (callback!=null)
{
prefixJson = true;
}
if (prefixJson)
{
generator.writeRaw(callback + "(");
}
objectMapper.writeValue(generator, value);
generator.flush();

if (prefixJson)
{
generator.writeRaw(");");
generator.flush();
}
}

and make sure you put entry in your servlet.xml file
<property name="defaultViews">
<list>
<bean class="com.views.utility.MappingJacksonJsonpView" />

About Me