I am having a problem, where I send a request with a Json body, and the parser is not changing that Json into the desired Java object, it is returning that object with all the parameters null:
This is the request from postman:
POST http://localhost:8084/api/user/user
body: {
"name": "Santiago",
"email": "yes",
"number": "4",
"password": "rftgybn",
"date_of_birth": "2024-11-06T12:30:00Z",
"location": "Medellin"
}
This is the request shown by my springboot filter I made (I made it so I could verify the request is correct, the problem existed before making that filter):
POST "/api/user/user", parameters={}
Request Body: {
"name": "string",
"email": "string",
"number": "string",
"password": "string",
"date_of_birth": "2024-11-07T11:27:15.086Z",
"location": "string"
}
This is my DTO object:
@Getter
@ToString
@NoArgsConstructor
public class UserRegisterRequestDTO {
@JsonProperty("name")
private String name;
@JsonProperty("email")
private String email;
@JsonProperty("number")
private String number;
@JsonProperty("password")
private String password;
@JsonProperty("date_of_birth")
private Date dateOfBirth;
@JsonProperty("location")
private String location;
}
This is my controller method that is being invoked:
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserControllerImplementation implements UserController {
@Override
@PostMapping(produces = "application/json")
public ResponseEntity<UserBasicDTO> createUser(@RequestBody UserRegisterRequestDTO user) {
System.out.println("nnCreating user");
System.out.println(user);
return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(user));
}
}
Those System.out.println() are printing the following:
Creating user
UserRegisterRequestDTO(name=null, email=null, number=null, password=null, dateOfBirth=null, location=null)
I have been trying for a day now, and I do not know what else to do. Please help, and thanks a lot!
4
Answers
Turns out, that when adding the @RequestBody annotation, I was importing the annotation from
Swagger
, not the annotation fromSpringframework.web.bind.annotation
.In Summary, I was importing the wrong @RequestBody. :(
It’s working for me with the same code you have.
Try adding
@AllArgsConstructor
and@Setter
on DTOs.Are you using the Body parameter in Postman with raw selected and JSON as the type?
If not, try using the following curl command into your terminal:
Try this:
For working objectMapper that deserialization and serialization in java. dto must have default constructor and constructor that all field in dto.