Spring 3 MVC with JSON via Jackson 2.0

Spring 3.1.2 adds support for automatic conversion to JSON via Jackson 2.x. There isn’t much that you need to do to make it work, with on caveat.

You need to be using at least Spring 3.1.2 to have Jackson 2.x support. Add the Jackson 2.x dependencies.

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.0.4</version>
        </dependency>

NOTE: If you only include the jackson-core artifact and do not include the jackson-databind artifact, your spring requests will return HTTP 406 errors and there will be no indication of what the real problem is.

What happens if you don’t include jackson-databind? The <mvc:annotation-driven/> tag will not instantiate a MappingJackson2JsonView because it has an import for com.fasterxml.jackson.databind.ObjectMapper. There is no message because it just thinks that you are not using that.

Your spring mvc context should already have the <mvc:annotation-driven/>.

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.appriss.jxp"/>
    <mvc:annotation-driven/>

    <!-- Resolves view names for views returned by controllers -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:viewClass="org.springframework.web.servlet.view.JstlView"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp"/>
</beans>

Create a controller method. There are 2 things that must be done. First, specify that the method does produce json as the output. That will map against the “accept-header: application/json”. Then have the method return an object instead of a ModelAndView object. Annotate that object with @ResponseBody.

    /**
     * Returns a json list of first names.
     * @param term the beginning part of the first name
     * @return json string array of first names
     */
    @RequestMapping(value = "/first", produces = "application/json")
    public @ResponseBody List<String> firstNames(@RequestParam String term) {
        return nameDao.getFirstNames(term);
    }

There you have it. The rest is automatic.

About these ads
This entry was posted in Java, json, Spring. Bookmark the permalink.

10 Responses to Spring 3 MVC with JSON via Jackson 2.0

  1. wesreisz says:

    Great stuff Norris!

  2. Andy Neira says:

    Hi all, I think a great framework.

    Currently I have a problem with jackson version 2.1. and spring3.1.2 mvc

    In version 1.9.8 previously operated.
    - In the servlet had configured as follows:

    - In the controller method that returns me json
    @RequestMapping(value = “/internal/newJson”,method=RequestMethod.POST,params = “action=combox”, produces=MediaType.APPLICATION_JSON_VALUE)
    @ModelAttribute(“contactForm”)
    public @ResponseBody ContactForm fillCombox(@ModelAttribute(“contactForm”) ContactForm contactForm){
    logger.info(” == JSON == “);
    logger.info(“contactForm.getIdDepartamento() : ” + contactForm.getIdDepartamento());
    contactForm.setProvinciaList(webFacade.listProvincias(contactForm.getIdDepartamento()));
    logger.info(“size :: ” + contactForm.getProvinciaList().size());
    return contactForm;
    }
    Already in jquery iterate and show on the screen.

    But in version 2.1 jackson

    I have the same but not the statement in the servlet.
    In this case not response json.

    Any additional settings?I’m missing? Please
    Thanks for you time.

    • Did you follow the steps above? Have you tried to set a breakpoint in your method to ensure that it is being reached. Have you looked at the request/response in firebug or something similar?

      • Andy Neira says:

        Good Morning Norris,
        Did you follow the steps above?
        Yes
        Have you tried to set a breakpoint in your method to ensure that it is being reached. ?
        Yes, show me log

        20:49:23,148 INFO [JsonController] contactForm.getIdDepartamento() : 1
        20:49:23,155 INFO [JsonController] size :: 2
        size total = 2

        breakpoint in response brings me the following.

        in js
        ———
        success: function(response){
        // we have the response
        alert(“response : ” + response);
        $(‘#idProvincia option’).remove();
        $(“#idProvincia”).append(options);
        },

        return alert :
        —————-
        not return json :(
        all page tag in html



  3. Andy Neira says:

    And thank you very much solve the problem.

    The problem was the annotation (@ModelAttribute(“contactForm”)) to keep the object in session.
    The method is solved:

    @RequestMapping(value = “/internal/newJson”,method=RequestMethod.POST,params = “action=combox”, produces=MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ContactForm fillCombox(@ModelAttribute(“contactForm”) ContactForm contactForm){

    logger.info(” JSON “);
    logger.info(“contactForm.getIdDepartamento() : ” + contactForm.getIdDepartamento());

    contactForm.setProvinciaList(webFacade.listProvincias(contactForm.getIdDepartamento()));
    logger.info(“size :: ” + contactForm.getProvinciaList().size());
    return contactForm;
    }

  4. elattari says:

    hello
    I Have a probleme
    when returning JSON the callback function not called

    Can you help me please

  5. elattari says:

    The probleme appears only in IE9

  6. Enrique says:

    Hi Norris, any idea about how to the ObjectMapper could delegate in Spring ConversionService?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s