Spring MappingJacksonJsonView, how to tell to use it instead of JSP view?

后端 未结 4 1750
慢半拍i
慢半拍i 2021-01-03 07:30

I\'m trying to use MappingJacksonJsonView with Spring 3.0, without success. I don\'t know what I\'m doing wrong, I think the problem is that I don\'t know how t

相关标签:
4条回答
  • 2021-01-03 08:12

    you will need to see ContentNegotiatingViewResolver,and set defaultviews property to MappingJacksonJsonView, and @ResponseBody uses HttpMessageConverter to instead of ViewSolver,see the differences between them http://ufasoli.blogspot.com/2013/08/viewresolver-vs-messageconverter-spring.html

    0 讨论(0)
  • 2021-01-03 08:29

    You should do it this way:

    In your xml file set the following: set

    <mvc:annotation-driven />
    

    After it you need to set Jackson serializer:

    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <list>
        <ref bean="jacksonMessageConverter"/>
      </list>
    </property>
    </bean>
    

    after it you can use it in your Controller:

    @RequestMapping(value="/getObjects",method = RequestMethod.POST)
         @ResponseBody
         public  List<MyObject> getCategories(){
         List<MyObject> objects = daoService.gettAllObjects();
         return objects;
        }
    
    0 讨论(0)
  • 2021-01-03 08:33

    Adding the following worked in my case

    <mvc:annotation-driven />
    
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
            <property name="order" value="0" />
        </bean>
    

    So basically we should try to resolve any view as a bean first

    0 讨论(0)
  • 2021-01-03 08:34

    Spring will use Accept header sent by the client to return most appropriate view. Here you will find my complete Spring MVC application that returns both JSON and XML.

    As you can see, I only needed:

    <mvc:annotation-driven />
    

    I also used the same annotations: @RequestMapping to map request to a method and @ResponseBody to tell Spring that what I am returning from the controller is the actual response. It might however need some tweaking/formatting, and here Spring takes care of marshalling your object into most appropriate type like JSON.

    0 讨论(0)
提交回复
热议问题