今天使用RequestBody接受前端传过来的参数,以前接受字符串数组非常成功,这次把形参改成了List<User>,原本以为顺利接受参数并映射成User的list结构,结果竟然在我取user.getId()时报了com.alibaba.fastjson.JSONObject cannot be cast to xxx的错。
前端:
$.ajax({
url : "/insertUser",
async : true,
cache : false,
type : "post",
contentType : "application/json; charset=UTF-8",
data : JSON.stringify(userList),
success : function(data) {
//...
}
});
后端:
@RequestMapping("/insertUser")
public void insertBlank(@RequestBody List<User> userList) {
User user = userList.get(0);
System.out.println(user.getId());
}
不知怎的,RequestBody接受参数不能直接转成想要的类,通过debug观察到userList接受到了一个JSONArray<JSONObject>的结构,根本没有转成List<User>.
搜索资料,发现要想用RequestBody直接映射到java对象,需要配置在配置springMVC注解驱动时配置fastJson转换器,看了看项目中的配置文件,这的配了这个东西。
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
但是与资料不同,正在开发的项目还对这个转换器设置了支持触发的类型application/json;charset=UTF-8。
观察一下
发送的请求为application/json; charset=UTF-8,
支持的类型为application/json;charset=UTF-8
发现端倪了,我发的请求类型中间多了一个空格!
去掉空格发送请求,结果:
我的user对象还是没有转换成功,还是一个一个JSONObject,但是请观察,JSONArray转换成了ArrayList。
嗯,配置的映射转换器生效了,结果表明,RequestBody能直接将json对象映射成java对象,但仅限于第一层的对象,至于嵌套的对象,则需要开发者自己去转换。
@RequestMapping("/insertUser")
public void insertUser(@RequestBody List<JSONObject> list) {
List<User> userList = list.stream().map(json -> JSONObject.toJavaObject(json, User.class)).collect(Collectors.toList());
service.insertUser(userList);
}