skip to Main Content

I’m writing a crud application using SpringBoot and Jquery with Ajax. And I’m getting the following exception:
(I’m getting an exception when I’m trying to add a new user)

.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of 
`ru.javamentor.predproject3.model.User` out of START_ARRAY token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of 
`ru.javamentor.predproject3.model.User` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]]

Here is my js. GET method works fine.

$(document).ready(function () {
  gettingListOfUsers();
  addingUser();
});

function gettingListOfUsers() {
  $.ajax({
     url: '/rest/users',
     type: 'GET',
     dataType: 'json',
     success: function (listOfUsers) {
        let userData = '';
        $.each(listOfUsers, function (index, user) {
            userData += '<tr>';
            userData += '<td>' + user.id + '</td>';
            userData += '<td>' + user.firstName + '</td>';
            userData += '<td>' + user.secondName + '</td>';
            userData += '<td>' + user.email + '</td>';
            userData += '<td>' + user.role + '</td>';
            userData += '<td> <button class="btn btn-info" data-toggle="modal">update</button> ' +
                '<a class="btn btn-danger" onclick="if (!(confirm('Are you sure you want to delete this user?'))) ' +
                'return false">delete</a></td>';

            userData += '</tr>';
        });

        $('#userTable2').html(userData);
    },

    error: function (error) {
        alert("Error");
    }
})
}

function addingUser() {
$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serializeArray();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: JSON.stringify(addingFormData),
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})
}

My programm don’t even get till controller. It falls in error block

@PostMapping(“/adding”)

public ResponseEntity<User> addingPost(@RequestBody User user) {

    HttpHeaders httpHeaders = new HttpHeaders();

    user.setPassword(passwordEncoder.encode(user.getPassword()));

    userService.addUser(user);

    return new ResponseEntity<>(user, httpHeaders, HttpStatus.CREATED);
}

2

Answers


  1. I could have a better idea if you post your controller.
    It seems like you are deserializing a json string into json object.
    If that is true, you have a malformed json string, it is possible you don’t have initial curly brace.

    EDITED

    I double checked and I think your issue is in JS code.

    $('#addingButton').on('click', function (event) {
        event.preventDefault();
    
        const addingFormData = $('#addingUserForm').serialize();
        // alert(addingFormData.length);
    
        $.ajax({
            url: '/rest/adding',
            type: 'POST',
            data: addingFormData,
            dataType: 'json',
            contentType: "application/json",
            success: function (responseData, status, jqXHR) {
                alert('User has been added successfully');
                gettingListOfUsers();
            },
            error: function () {
                alert('Error');
            }
        })
    })
    
    Login or Signup to reply.
  2. The error message says exactly what’s wrong. It wants to create a User out of a piece of jason (expecting a jason object), but the string you send from the request starts with [, which denotes an array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search