Spring MVC JSON view

For Ajax-based web application, one of the most popular ways for message transfer is JSON (JavaScript Object Notation). JSON provides a pretty name/value pair data format which is easy to generate and parse.

With the popular using Spring framework. It would be really useful to integrate Spring MVC view with JSON. Spring already provides several view resolvers, which enable us to render models in a browser, such as: JSPs, Velocity templates and XSLT views.

To add JSON view to the Spring MVC, we need create a class: JSONView



  1. public class JSONView implements View {  
  2. private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json";  
  3. private static final String DEFAULT_JAVASCRIPT_TYPE = "text/javascript";  
  4. private JSONObject jsonObject;  
  5.   
  6. public JSONView(JSONObject jsonObject) {  
  7.  super();  
  8.  this.jsonObject = jsonObject;  
  9. }  
  10.   
  11. public JSONView() {  
  12.  super();  
  13.  this.jsonObject = null;  
  14. }  
  15.   
  16. public String getContentType() {  
  17.  return DEFAULT_JSON_CONTENT_TYPE;  
  18. }  
  19.   
  20. public void render(Map model, HttpServletRequest request,  
  21.  HttpServletResponse response) throws Exception {  
  22.  if (this.jsonObject == null) {  
  23.   this.jsonObject = JsonUtil.fromMap(model);  
  24.  }  
  25.   
  26.  boolean scriptTag = false;  
  27.  String cb = request.getParameter("callback");  
  28.  if (cb != null) {  
  29.   scriptTag = true;  
  30.   response.setContentType(DEFAULT_JAVASCRIPT_TYPE);  
  31.  } else {  
  32.   response.setContentType(DEFAULT_JSON_CONTENT_TYPE);  
  33.  }  
  34.   
  35.  PrintWriter out = response.getWriter();  
  36.  if (scriptTag) {  
  37.   out.write(cb + "(");  
  38.  }  
  39.  out.write(this.jsonObject.toString());  
  40.  if (scriptTag) {  
  41.   out.write(");");  
  42.  }  
  43. }  
  44. }  



And this is fromMap function in JsonUtil

public static JSONObject fromMap(Map model) {
 JSONObject jsonObject = new JSONObject();

 try {
  Iterator ite = model.keySet().iterator();
  while (ite.hasNext()) {
   String key = ite.next();
   jsonObject.put(key, model.get(key));
  }
 } catch (Exception e) {
  log.error("call fromMap failed ");
 }

 return jsonObject;
}

And in the controller side, we can pass JOSNObject to create a JSONView. Or we can also pass MAP to create JSONView.

Map map = new HashMap();
 map.put("success", "true");
 map.put("info", "Succeed create this audit object");
 return new ModelAndView(new JSONView(), map);
OR
BaseSearchResult searchResult = auditService.getList(listAuditInfo);
 AuditUtil auditUtil = new AuditUtil(searchResult); 
 return new ModelAndView(new JSONView(auditUtil.toJSONObject()));

0 comments: