現象:Controller 方法加 @ResponseBody 返回對象,瀏覽器/前端報 **HTTP 406 Not Acceptable**,後端控制台無異常。根因:**Spring 默認消息轉換器無法匹配請求 Accept 頭**,或 **FastJson 轉換器未正確註冊/優先級不夠**。
Accept: application/json (或瀏覽器默認 text/html)HttpMessageConverter 列表,尋找 canWrite(clazz, mediaType) 返回 true 的轉換器HttpMediaTypeNotAcceptableException → 返回 406<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- FastJson 轉換器,置於首位提升優先級 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value> <!-- 關鍵:兼容瀏覽器直接訪問 Accept=text/html -->
</list>
</property>
<property name="features">
<array>
<value>WriteMapNullValue</value> <!-- 輸出 null 字段 -->
<value>WriteNullStringAsEmpty</value> <!-- null 字串輸出 "" -->
<value>WriteNullListAsEmpty</value> <!-- null 集合輸出 [] -->
<value>WriteNullNumberAsZero</value> <!-- null 數字輸出 0 -->
<value>WriteNullBooleanAsFalse</value> <!-- null 布爾輸出 false -->
<value>DisableCircularReferenceDetect</value> <!-- 禁用循環引用檢測 (提升性能,慎用) -->
<value>BrowserCompatible</value> <!-- 瀏覽器兼容 (特殊字符轉義) -->
</array>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Spring Boot 內置 HttpMessageConvertersAutoConfiguration,**無需 XML**,僅需引入依賴即可自動生效:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version> <!-- 或 2.x 版本 -->
</dependency>
若需自定義配置,創建配置類:
@Configuration
public class FastJsonConfig {
@Bean
public HttpMessageConverter<?> fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.BrowserCompatible
);
config.setCharset(StandardCharsets.UTF_8);
// 關鍵:支持 text/html 避免 406
converter.setSupportedMediaTypes(Arrays.asList(
MediaType.APPLICATION_JSON_UTF8,
MediaType.TEXT_HTML
));
converter.setFastJsonConfig(config);
return converter;
}
}
| 根因 | 現象 | 解決 |
|---|---|---|
| FastJson 轉換器未生效 | 返回 406、或用 Jackson 輸出格式不符預期 | 檢查依賴、配置類、register-defaults="true" 保留默認轉換器 |
| Accept 頭為 text/html | 瀏覽器直接訪問 API 地址報 406 | FastJson 配置 supportedMediaTypes 添加 text/html |
| 返回類型為 List/Map 非 Bean | 泛型擦除導致轉換器匹配失敗 | 使用 Result<T> 包裝、或配置 fastjson.autoTypeSupport |
| 循環引用導致序列化失敗 | 控制台報錯、無響應 | 開啟 DisableCircularReferenceDetect、或 DTO 斷開循環 |
| Spring Boot 3 + FastJson 1.x 不兼容 | 啟動報錯/無效 | 升級 FastJson 2.x、或遷移至 Jackson (Spring Boot 3 默認) |