第一步,引入jackson.jar,并加入spring配置文件
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
第二步,在要转换的方法参数前加@RequestBody
method(@RequestBody Bean bean)
第三步,前台发送请求,注意,数据需要为json格式字符串,否则,会出现以下各种错误
1.Jackson Unexpected character ('h' (code 104)): expected a valid value
2.Can not deserialize instance of com.fhsoft.model.Question out of START_ARRAY token
3.NetworkError: 400 Bad Request
4.HTTP status 400 The request sent by the client was syntactically incorrect
正确写法如下
var data = $("#form").serializeArray();
data = convertToJson(data);
$.ajax({
type: "POST",
url: "saveQuestionIndex.do",
data: JSON.stringify(data),
dataType: 'json',
contentType:'application/json;charset=UTF-8', //contentType很重要
success: function(data){
}
});
/**
* 将表单对象转为json对象
* @param formValues
* @returns
*/
function convertToJson(formValues) {
var result = {};
for(var formValue,j=0;j<formValues.length;j++) {
formValue = formValues[j];
var name = formValue.name;
var value = formValue.value;
if (name.indexOf('.') < 0) {
result[name] = value;
continue;
} else {
var simpleNames = name.split('.');
// 构建命名空间
var obj = result;
for ( var i = 0; i < simpleNames.length - 1; i++) {
var simpleName = simpleNames[i];
if (simpleName.indexOf('[') < 0) {
if (obj[simpleName] == null) {
obj[simpleName] = {};
}
obj = obj[simpleName];
} else { // 数组
// 分隔
var arrNames = simpleName.split('[');
var arrName = arrNames[0];
var arrIndex = parseInt(arrNames[1]);
if (obj[arrName] == null) {
obj[arrName] = []; // new Array();
}
obj = obj[arrName];
multiChooseArray = result[arrName];
if (obj[arrIndex] == null) {
obj[arrIndex] = {}; // new Object();
}
obj = obj[arrIndex];
}
}
if(obj[simpleNames[simpleNames.length - 1]] ) {
var temp = obj[simpleNames[simpleNames.length - 1]];
obj[simpleNames[simpleNames.length - 1]] = temp;
}else {
obj[simpleNames[simpleNames.length - 1]] = value;
}
}
}
return result;
}
其中,convertToJson是网上直接拷过来的,用了一下发现会有BUG,对于多选值,如checkbox,只会
记录最后一个值,把对应代码修改如下:
if (name.indexOf('.') < 0) {
if(result[name]) {
result[name] = result[name] + "," + value;
} else {
result[name] = value;
}
continue;
}