1

I am using Spring boot I try to create a new Student.

@RequestMapping(path="/student/create", method=RequestMethod.POST)<br>
     public ResponseEntity<String> createStudent(@RequestBody Long nummer, String firstname, String lastname){<br>
      service.createStudent(matrikelnummer, vorname, nachname);<br>
      return new ResponseEntity<String>("gut gemacht", HttpStatus.OK);

Here my RequestBody with RESTCLIENT

{"nummer":15557,"firstname":"toti","lastname":"Innna"}

I have this Error:

{"timestamp":"2019-12-20T19:41:30.083+0000","status":400,"error":"Bad Request","message":"JSON parse error: Cannot deserialize instance of java.lang.Long out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.Long out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]","trace":"org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.lang.Long out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.Long out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]\r\n\tat

1 Answer 1

4

In your example the mapper expects the body to present a Long object, but you pass it a Student object. This does not match, so it throws an exception.

It is not necessary to list all the fields of the students as separate method arguments, you can just pass a Student object as RequestBody argument. The object mapper will then try to resolve a Student instance from the provided JSON.

Example:

@RequestMapping(path="/student/create", method=RequestMethod.POST)
public ResponseEntity<String> createStudent(@RequestBody Student student){
    service.createStudent(student);
    return new ResponseEntity<String>("gut gemacht", HttpStatus.OK);
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Poeterjan Thank you first. But the problem is, I defined the method in my service class.
If you want to use the full JSON as a request body, you will need the Student object as parameter in the API. If you want to use different parameters instead, try to use @RequestParameter instead of RequestBody (for all parameters).
or service.createStudent(student.getMatrikelnummer(), student.getVorname(), student.getNachname());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.