Spring 4 and Rest WS integration

守給你的承諾、 提交于 2019-12-01 03:54:26

You are currently using the MappingJacksonJsonView which is designed to work with Jackson1 .

You mention the following:

I am not using Jackson 1 api's. jars in my lib are, jackson-core-2.0.2, jackson-annotation-2.3.0, jackson-bindings 2.3.0.

Which means you have Jackson2 on your classpath. Jackson1 and Jackson2 aren't compatible (different packages, different classes etc.).

You have 2 possible solutions

  1. Don't use Jackson2 and switch your dependencies to Jackson1
  2. Replace the MappingJacksonJsonView with the MappingJackson2JsonView

For Spring4 Rest + Json POC The following App Context is enough

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">
    <context:component-scan base-package="org.name.controller" />
    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />
    <mvc:resources location="/statics/" mapping="/statics/**"/>
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Make sure you have dependency for Jackson (e.g. in maven)

<!-- jackson so spring mvc will handle json responses out of the box -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.0</version>
</dependency>

You do not specifically need to define MappingJackson2JsonView; MappingJackson2HttpMessageConverter/MappingJacksonHttpMessageConverter will be created automatically when jackson is the the class path (the default is only when ContentType/Accept are application/json).

Jackson1 is deprecated, but still supported if from any reason you are limited to Jackson1 See Spring 4 docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!