Hello,
In this mini article, we will explain the 2 ways to generate JSON from a web application based on Spring MVC:
– with the “JSON view resolver” of Spring;
– without the “JSON view resolver” of Spring i.e. with the json-lib-2.3-jdk15.jar;
Reminder: Classic handler returning to a JSP page due to ‘JstlView’
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- .... --> <!-- ################### SPRING MVC VIEW RESOLVER ################### --> <!-- IF the Controller returns a logical view name="myList" THEN the ViewResolver will return the file "/WEB-INF/jsp/myList.jsp" END IF --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> <property name="order"><value>2</value></property> </bean> <!-- .... --> </beans>
… and the view resolver JstlView is used in the spring controller like:
/** * Controler SPRING MVC: Class to handle the web requests. * * @author HOZVEREN * */ public class MyController extends MultiActionController { //... /** * <p> Handler of Spring controller using the Spring Internal Resource view resolver</p> */ public ModelAndView handleWithSpringSpringInternalResourceResolver(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InterruptedException { Object bean = null; // .... //Store the data in request's attribute request.setAttribute("ControllerData", data); // Return the view name (to internal resolver) return new ModelAndView("/myJSPPage"); } //... }
JSON with the “JSON view resolver” of Spring
Often the web applications based on Spring MVC, use the “JSON view resolver” of Spring:
<!-- .... --> <!-- ################### SPRING JSON RESOLVER ################### --> <bean id="jsonResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order"><value>1</value></property> </bean> <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"> <property name="contentType"> <value>text/html</value> </property> </bean> <!-- .... --> </beans>
… and the view resolver JsonView is used in the spring controller like:
//... /** * <p> Handler of Spring controller using the Spring JSON resolver</p> */ public ModelAndView handleWithSpringJsonResolver(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InterruptedException { Object bean = null; // .... Map<String, Object> model = new HashMap<String, Object>(); model.put("success", "true"); model.put("data", bean); return new ModelAndView("jsonView", model); } //...
JSON without the “JSON view resolver” of Spring
It is possible to use an external library like json-lib-2.3-jdk15.jar to generate “manually” the JSON instead of the Spring json resolver. So, it is not necessary to configure a ViewResolver in spring web context.
First, we wil create a class ListOfDocuments containing a number of Document:
public class ListOfDocuments{ //... // Convert and return the JSON object of current object public JSONObject getJSON(){ JSONObject jsonObj = new JSONObject(); JSONArray jsonArray = new JSONArray(); for(Document doc : this.documents){ jsonArray.add(doc.getJSON()); } jsonObj.put("listId", this.listId); jsonObj.put("items", jsonArray); return jsonObj; } //... }
public class Document{ //... // Convert and return the JSON object of current object public JSONObject getJSON(){ JSONObject jsonObj = new JSONObject(); jsonObj.put("documentId", this.documentId); jsonObj.put("reference", this.reference); return jsonObj; } //... }
… then, the spring controller could generate the JSON by directly calls the appropriate methods:
//... /** * <p> Handler of Spring controller using the external JSON generator json-lib-2.3-jdk15.jar</p> */ public ModelAndView handleWithExternalJSONGenerator(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InterruptedException { ListOfDocuments bean = null; // .... // { reponse.setContentType("application/json"); obj.write(reponse.getWriter()); } return null; } //...
More, it is possible to write a JSON Configuration to specify the behaviour during the jsonization:
private static JsonConfig jsonConfigValidation; { jsonConfigValidation = getDefaultJsonConfig(); jsonConfigValidation.setExcludes(new String[]{"errorPresent"}); } // Generic jsonConfig private JsonConfig getDefaultJsonConfig(){ JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Calendar.class, new JsonValueProcessor(){ @Override public Object processArrayValue(Object value, JsonConfig config){ return process(value, config); } @Override public Object processObjectValue(String key, Object value, JsonConfig config){ return process(value, config); } private Object process(Object value, JsonConfig config){ String txtValue = "12/12/2012"; // txt value of calendar object } }); return config; }
This JsonConfig could be used during the creation of JsonObjectlike:
JSONObject jsonObj = new JSONObject(); jsonObj.put("errors", JSONArray.fromObject(errors, jsonConfigValidation));
That’s all !!!!
Huseyin OZVEREN
Koennte miг mal irgendwer sagen, wo ich andere solche Aufsaetze zu diesem Geɡenstand aufgabeln kann?