Miha Jamsek Miha Jamsek - 22 days ago 6
Ajax Question

Spring Boot send array of objects to controller with ajax

So, I followed some other questions on how to set spring boot controller to parse incoming data, which is array of objects.

I am sending data in next form:

var myData = [ {lang_id : 1, title : "blabla", description : "blablabla"}, {lang_id : 2, title : "der text", description : "der text"}, ... ]

$.ajax({
url: "/test2",
data: JSON.stringify(myData),
type: "POST",
dataType:"json",
contentType:'application/json'
,success : function(res){
console.log("ok!", res.data);
}
,error : function(a,b,c){
console.log("err!", a, b, c);
}
});


According to other answers, i have made my response and response wrapper object.

public class Response {
private Integer lang_id;
private String title;
private String description;
//getter and setters
}

public class RequestWrapper {
private List<Response> items;
//getters and setters
}


Then, i set my controller as follows:

@PostMapping(value="/test2")
public @ResponseBody RequestWrapper postIt(@RequestBody RequestWrapper req) {
System.out.printf("\n\n%s\n\n", req);
return req;
}


Any every single answer had solution like this, yet this one doesn't work for me. I get following error:


org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Can not deserialize instance of
com.mypackage.controllers.RequestWrapper out of START_ARRAY token;
nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Can not
deserialize instance of com.mypackage.controllers.RequestWrapper out
of START_ARRAY token


I don't know what else to try.

Answer Source

I think it should be:

public @ResponseBody RequestWrapper postIt(@RequestBody Response[] req)

Given your RequestWrapper POJO, the correct JSON is of the following form:

{
  "items": [
    ...
  ]
}