Json array deserialization in Spring MVC

I am posting a list of json objects and trying to deserialize it in my Spring controller. But all the time I get the "Bad Request" error and the results are in status code 415. However, my json array is valid.

json -

{"users": [{"userName": "john", "email": " john@gmail.com ", "user_id": "u223344"}, {"userName": "Smith", "email": " smith@gmail.com "," user_id ":" u223345 "}]}

Ajax call is as follows:

$.ajax({
url: $("#addNewUser").attr("action"),
data: JSON.stringify({users : dataToSend}),
dataType: 'json',
type: "POST",   
beforeSend: function(xhr) {
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("Content-Type", "application/json");
}, 
success: function(data){ 
       alert('success=  ' + data);
},
error:function(data,status,er) { 
    alert("error: "+ data.responseText +" status: "+status+" er:"+er);
}

});

. User UserWrapper -

public class User {

private String email;

private String userName;

private String user_id;

//getters and setters

}

public class UserWrapper {

private List<User> userList;

//getter and setter

}

, , Spring MVC -

@RequestMapping(value="/user/add", method=RequestMethod.POST, 
        produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void createTeamMember(@RequestBody UserWrapper userWrapper) {

    try{
        for(User user : userWrapper.getUserList()){
            System.out.println(user.getEmail());
            }
    }catch(Exception ex){
        ex.printStackTrace();
    }

}

jackson-core jackson-mapper pom.xml. Spring 4.0.3. .

+4
3

, @RequestBody POJO UserWrapper

@RequestMapping(value="/task/add", method=RequestMethod.POST, 
        produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void createTeamMember(@RequestBody UserWrapper userWrapper) {
    // Code to create members
}
+1

@shazin, , , , , , .

, usersList UserWrapper users, JSON.

, , .

+1

, 415 - Unsupported Media Type. , , , .

, jquery 1.5+, , sendSend() .

,

$.ajax({
        url:api,
        ....
        contentType: "application/json"
    });

, , .

400-Bad Request, .

0

Source: https://habr.com/ru/post/1568697/


All Articles