user3411781 user3411781 - 1 month ago 8
Ajax Question

Sending JSON List Of Object to Spring MVC controller

I have an issue with sending a List Of Objects to Spring MVC controller .

The list of object is like this

[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]


And I send the above data with the following AJAX code:

$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : JSON.stringify(adresses.toArray()),
});


When I use this form of ajax, it worked for me and the format sended is as follow:

Request Payload :
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]


Yes, even the above one is worked, when i send it like as follow:

$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : {adresseList : JSON.stringify(adresses.toArray())},
});


It doesn;t work for me. The sending data is look like


listAdresse=%5B%7B%22alias%22%3A%221%22%2C%22rue%22%3A%22Rue+de+la+Senette%22%2C%22codePostal%22%3A%2278955%22%2C%22ville%22%3A%22Carri%C3%A8res-sous-Poissy%22%2C%22rueComplement%22%3A%22%22%7D%5D
Response Headersview source


And, It gave an error:
400 bad request


Here, my controller

@RequestMapping(value = "creerlivraison/ajouterclientBD",method=RequestMethod.POST)
public String ajouterClientBD(@RequestBody Adresse[] listAdresse, Principal principal) {
for (Adresse adresse : listAdresse) {
System.out.println(adresse);
}
return "ok";
}


I want to know that "What is the difference between the two ajax request?", why the request payload is formatted when I wrap the data inside the braquets {} and specify listAddress.

Here is screen capture:

Object Data

Answer

http://api.jquery.com/jquery.ajax/

data

Type: PlainObject or String or Array

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

In this instance,

  • JSON.stringify(adresses.toArray()) is string, just keep the JSON format.
  • {adresseList : JSON.stringify(adresses.toArray())} is an object, so it is converted to a query string.
Comments