SpringMVC返回Json失败,请检查是否配置了Jackson

来源:互联网 发布:学网络编程 编辑:程序博客网 时间:2024/05/16 11:29

背景

需要一套干净的Spring+Spring MVC+Mybatis框架,框架写到返回Json的环节报错了。


问题

无法Json,报406


解决

需要配置Json工具包,这里用Jackson

Maven Jackson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.6.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.0</version>
        </dependency>

工程环境SpringMvc 4.x,官网:www.fhadmin.org 不兼容Jackson2.9最新版。这里特应用2.6版本

Spring Mvc配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    <!--Begin:使用Jackson 2.x的配置,需要导入的jar包:jackson-core-xxx.jar、jackson-annotations-xxx.jar、jackson-databind-xxx.jar-->
    <!--通过处理器映射DefaultAnnotationHandlerMapping来开启支持@Controller注解-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <!--通过处理器适配器AnnotationMethodHandlerAdapter来开启支持@RequestMapping注解-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- 设置返回字符串编码 -->
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name = "supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <!-- json转换器 -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    <!--End:使用Jackson 2.x的配置,需要导入的jar包:jackson-core-xxx.jar、jackson-annotations-xxx.jar、jackson-databind-xxx.jar-->

好了,重启不报错(一般就是jar宝冲突),就可以正常接收到@ResponseBody返回的Json了。


以上配置,带来好运,祝好    !