您的位置:首页 > 编程语言 > Java开发

SpringMVC @RequestBody processing Ajax requests

2014-11-06 22:24 302 查看
1 problem description

Recently in the debugging code and found the following problems:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected character ('c' (code 99)): expected a valid value (number,
String, array, object, 'true', 'false' or 'null').

The front is a Ajax request, the data is a JSON object.

Background found the wrong is generally JSON data
format transfer problems.

The object passed to the Java terminal 2

In the SpringMVC environment, @RequestBody receiver is a Json string object, not a Json object. However, in the Ajax request often pass are Json objects, and later found withJSON.stringify(data)The
way can the object into a string. At the same time the Ajax request to the specifieddataType: "json",contentType:"application/json"This
can easily be an object to the Java end, use @RequestBody to bind objects

3 how will the List object to the Java terminal:

<script type="text/javascript">
$(document).ready(function(){
var saveDataAry=[];
var data1={"userName":"test","address":"gz"};
var data2={"userName":"ququ","address":"gr"};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
type:"POST",
url:"user/saveUser",
dataType:"json",
contentType:"application/json",
data:JSON.stringify(saveData),
success:function(data){

}
});
});
</script>


JSON.stringify() : Convert the object to a JSON string.

JSON.parse(): The string JSON is converted to JSON objects.

Java:

@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})
@ResponseBody
public void saveUser(@RequestBody List<User> users) {
userService.batchSave(users);
}


This is not possible. Because spring MVC does not automatically translate into a
List object. To the background, List is of type LinkedHashMap.

But using the array can receive User[], as follows:

@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})
@ResponseBody
public void saveUser(@RequestBody User[] users) {
userService.batchSave(users);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: