spring 4.1获取json时406错误

spring mvc 返回json数据本以为与string一样简单,谁知竟用了大概6个小时才解决问题。


这里简单描述一下历程,先声明一下我是小白,原理一些底层的我是不懂的。


问题描述:使用@ResponseBody注解获取json时出现406错误, 浏览器信息如下:
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()

问题原因:缺少配置信息不能正确处理json(不一定是最准确的描述)

解决过程:网上找了很多,大多是spring3.x的,4.x的也有不过大部分不适用于我,最终找到了一个帮助到我的文章,见参考

问题解决:参考
我使用的intellij 2016创建的maven项目,spring4.1.6(5.x已经出了)。解决这个问题时一定要注意版本。


pom.xml中使用了2.5.4的jackson,如下:

<jackson.version>2.5.4</jackson.version>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson.version}</version>
</dependency>

servlet.xml中添加的配置如下:

<context:annotation-config/>
<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <!--json处理-->
        <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

controller给大家展示一下,这里要注意bean的private属性要有getter、setter,代码的很多参数写死了,只是给大家参考一下。

@RequestMapping(value = "/getGoodsList", method = RequestMethod.GET)
@ResponseBody
public List<GoodsDO> getGoodsList(String userID, String region) {
    List<GoodsDO> goodsDOList = this.goodsService.getGoods("818be6db-0a8a-4944-8d2b-d86934cd1666"
            , "dalian", GoodsKind.digitalProduct, SortBasis.PRICEASC, 1);
    return goodsDOList;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值