前后端分离架构下,Controller 接收 application/json 请求体是高频场景。本文涵盖注解用法、消息转换器配置、依赖坐标、List 类型反序列化坑点、实体类设计建议及 C# 客户端调用示例。
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "application/json")
public ReturnType handle(@RequestBody ParamType param, HttpServletRequest request) throws Exception {
// 业务逻辑
}
@RequestBody:将请求体绑定到参数对象consumes:限定 Content-Type,提升匹配精度SpringMVC 默认已注册 MappingJackson2HttpMessageConverter(需 Jackson 依赖),无需额外 XML 配置。若用 XML 配置:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- 文件上传若需 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
直接接收 List<MyEntity> 时,Jackson 会反序列化为 List<LinkedHashMap>,需手动转换:
ObjectMapper mapper = new ObjectMapper();
List<MyEntity> list = new ArrayList<>();
for (Object item : rawList) {
list.add(mapper.convertValue(item, MyEntity.class));
}
更优方案:定义包装 DTO class RequestDTO { List<MyEntity> items; },直接接收 DTO,利用泛型类型信息自动反序列化。
| 场景 | 问题 | 对策 |
|---|---|---|
| C# 客户端调用 | DateTime 序列化格式不兼容 | 实体类日期字段用 String 接收,服务端再解析 |
| 字段命名 | 驼峰 vs 下划线 | 统一加 @JsonProperty 或配置 PropertyNamingStrategy.SNAKE_CASE |
| 空值处理 | null 字段是否序列化 | @JsonInclude(JsonInclude.Include.NON_NULL) |
string dataJsonString = JsonConvert.SerializeObject(entity); byte[] buffer = Encoding.UTF8.GetBytes(dataJsonString); HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uri); httpReq.Method = "POST"; httpReq.ContentType = "application/json; charset=utf-8"; httpReq.ContentLength = buffer.Length; httpReq.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse(); string result = new StreamReader(httpResp.GetResponseStream(), Encoding.UTF8).ReadToEnd();
@RequestBody + Jackson 依赖 + consumes=application/jsonFAIL_ON_UNKNOWN_PROPERTIES=false 增强兼容性