1. Description of the problem
The following issues were discovered recently when debugging code with the foreground:
Org.springframework.http.converter.HttpMessageNotReadableException:Could not read json:unexpected character (' C ' ( Code): expected a valid value (number, String, array, object, ' true ', ' false ' or ' null ').
The foreground is an AJAX request, and the data is a JSON object.
Background found that this error is generally passed the JSON data format is problematic.
2. Upload object to Java end
In a SPRINGMVC environment, @RequestBody receives a string of JSON objects instead of a JSON object. However, in the AJAX request is often the JSON object, and later found that json.stringify (data) can be used to make the object into a string. Also specify DataType when Ajax requests : "JSON", ContentType: "Application/json" so that you can easily upload an object to the Java side, Use @requestbody to bind objects
3. How to upload a list object to the Java side:
<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) {
}
});
Json.stringify (): Converts an object to a JSON string.
Json.parse (): Converts a JSON string into a JSON object.
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 is not automatically converted to a List<user> object. After uploading to the background, the list is the Linkedhashmap type.
However, you can use an array to accept user[], as follows:
@RequestMapping (value = "Saveuser", method = {Requestmethod.post}})
@ResponseBody public
void Saveuser (@ Requestbody user[] Users {
userservice.batchsave (users);