JavaBlog.fr / Java.lu DEVELOPMENT,Java,Spring,WEB Java/Spring/JSON: Generate JSON with/without viewresolver jsonview / with json-lib-2.3-jdk15

Java/Spring/JSON: Generate JSON with/without viewresolver jsonview / with json-lib-2.3-jdk15

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’

01<?xml version="1.0" encoding="UTF-8"?>
05    xsi:schemaLocation="http://www.springframework.org/schema/beans
07     
08<!-- .... -->
09 
10    <!-- ################### SPRING MVC VIEW RESOLVER  ################### -->
11    <!--
12        IF the Controller returns a logical view name="myList" THEN
13            the ViewResolver will return the file "/WEB-INF/jsp/myList.jsp"
14        END IF
15     -->
16    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
17        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
18        <property name="prefix" value="/WEB-INF/jsp/"></property>
19        <property name="suffix" value=".jsp"></property>
20        <property name="order"><value>2</value></property>
21    </bean>
22<!-- .... -->
23 
24</beans>

… and the view resolver JstlView is used in the spring controller like:

01/**
02 * Controler SPRING MVC: Class to handle the web requests.
03 *
04 * @author HOZVEREN
05 *
06 */
07public class MyController extends MultiActionController {
08//...
09    /**
10     * <p> Handler of Spring controller using the Spring Internal Resource view resolver</p>
11     */
12    public ModelAndView handleWithSpringSpringInternalResourceResolver(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InterruptedException {
13        Object bean = null; // ....
14        //Store the data in request's attribute
15        request.setAttribute("ControllerData", data);
16         
17        // Return the view name (to internal resolver)
18        return new ModelAndView("/myJSPPage");
19    }
20//...
21}

JSON with the “JSON view resolver” of Spring
Often the web applications based on Spring MVC, use the “JSON view resolver” of Spring:

01<!-- .... -->
02    <!-- ################### SPRING JSON RESOLVER ################### -->
03    <bean id="jsonResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
04        <property name="order"><value>1</value></property>
05    </bean>
06 
07    <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
08        <property name="contentType">
09            <value>text/html</value>
10        </property>
11    </bean>
12<!-- .... -->
13 
14</beans>

… and the view resolver JsonView is used in the spring controller like:

01//...
02    /**
03     * <p> Handler of Spring controller using the Spring JSON resolver</p>
04     */
05    public ModelAndView handleWithSpringJsonResolver(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InterruptedException {
06        Object bean = null; // ....
07        Map<String, Object> model = new HashMap<String, Object>();
08        model.put("success", "true");
09        model.put("data", bean);
10        return new ModelAndView("jsonView", model);
11    }
12 
13//...

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:

01public class ListOfDocuments{
02//...
03    // Convert and return the JSON object of current object
04    public JSONObject getJSON(){
05        JSONObject jsonObj = new JSONObject();
06        JSONArray jsonArray = new JSONArray();
07        for(Document doc : this.documents){
08            jsonArray.add(doc.getJSON());
09        }
10        jsonObj.put("listId", this.listId);
11        jsonObj.put("items", jsonArray);
12        return jsonObj;
13    }
14//...
15}
01public class Document{
02//...
03    // Convert and return the JSON object of current object
04    public JSONObject getJSON(){
05        JSONObject jsonObj = new JSONObject();
06        jsonObj.put("documentId", this.documentId);
07        jsonObj.put("reference", this.reference);
08        return jsonObj;
09    }
10//...
11}

… then, the spring controller could generate the JSON by directly calls the appropriate methods:

01//...
02    /**
03     * <p> Handler of Spring controller using the external JSON generator json-lib-2.3-jdk15.jar</p>
04     */
05    public ModelAndView handleWithExternalJSONGenerator(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, InterruptedException {
06        ListOfDocuments bean = null; // ....
07        //
08        {
09            reponse.setContentType("application/json");
10            obj.write(reponse.getWriter());
11             
12        }
13        return null;
14    }
15//...

More, it is possible to write a JSON Configuration to specify the behaviour during the jsonization:

01private static JsonConfig jsonConfigValidation;
02{
03    jsonConfigValidation = getDefaultJsonConfig();
04    jsonConfigValidation.setExcludes(new String[]{"errorPresent"});
05}
06 
07// Generic jsonConfig
08private JsonConfig getDefaultJsonConfig(){
09    JsonConfig config = new JsonConfig();
10    config.registerJsonValueProcessor(Calendar.class, new JsonValueProcessor(){
11        @Override
12        public Object processArrayValue(Object value, JsonConfig config){
13            return process(value, config);
14        }
15             
16        @Override
17        public Object processObjectValue(String key, Object value, JsonConfig config){
18            return process(value, config);
19        }
20         
21        private Object process(Object value, JsonConfig config){
22            String txtValue = "12/12/2012"; // txt value of calendar object
23        }
24         
25    });
26    return config;
27}

This JsonConfig could be used during the creation of JsonObjectlike:

1JSONObject jsonObj = new JSONObject();
2jsonObj.put("errors", JSONArray.fromObject(errors, jsonConfigValidation));

That’s all !!!!

Huseyin OZVEREN

1 thought on “Java/Spring/JSON: Generate JSON with/without viewresolver jsonview / with json-lib-2.3-jdk15”

Leave a Reply to www.kurtcesarkilar.tv Cancel reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post