天天看點

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;
}