'Java @requestBody doesn't work, dto empty

For some reason java can't map DTO with requestBody and all values are default ones, as for request it works, with payload for ex. "{"productId":1,"commitment":6,"returnMonths":"2"}"

DTO

 @Data
    public class Request {
        private int productId;
        private int commitment;
        private String returnMonths;
    
        // contructers
    }

Controller :

@PostMapping(value = "/calculate", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String calculatePrice(@RequestBody Request request) {
        productService.calculatePrice(request);
        return "Success";
    }

front request:

submit: async function() {
      let request = {
        productId: this.productSelected,
        commitment: this.optionSelected,
        returnMonths: this.input
      };
      let data = await getCalculation(request);
      console.log(data);
    }

DTO maps as: productId : 0 commitment : 0 returnMonths : null



Solution 1:[1]

Tried an exact copy of your code and it worked when tested with Postman. This makes me think it's either something to do with the FE or maybe some issue in the service. I'd check if the Frontend really sends the data.

Solution 2:[2]

Try to annotation Request class with @AllArgsConstructor like:

@AllArgsConstructor
 @Data
    public class Request {
        private int productId;
        private int commitment;
        private String returnMonths;
    }

Solution 3:[3]

If your request body contains properties that is date such as LocalDateTime, make sure to format it in your DTO using @JsonFormat(pattern="") respecting the input value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pks9906
Solution 2 krishnkant jaiswal
Solution 3 Lakpriya Senevirathna