0

I have a Java SpringBoot backend server and I wanted to test the controller classes with curl. However, whenever I send a request with the following format (in a powershell terminal):

curl --request POST --header "Content-Type: application/json" --data '{\"key\": 5}' http://localhost:8080/request

All the numerical values are changed to zeroes. And if in the DTO class I change them to Integer instead of int, then they are received as null. For strings, everything works perfectly.

This is what my controller methodlooks like:

@RestController
@RequestMapping("/request")
class MyController {
    @PostMapping
    public ResponseEntity<MuseumTO> createMuseum(@RequestBody RequestDTO request) {
        System.out.println(request.key);

        // ...
    }
}

And the DTO class:

class RequestDTO {
    public int key
}

GET requests work fine, and I've tried with two different backends, so I assume my problem is coming from the curl request's format. However, I've looked online and from what I've seen this is supposed to work.

Thibaut B.
  • 172
  • 1
  • 12
  • Did you tried to create proper property with setter and getter? Maybe JSON deserializer doesn't work with fields? – talex Nov 16 '22 at 17:01
  • @talex Yes, I just tried making getters and setters and a constructor also but it didn't fix the issue. – Thibaut B. Nov 16 '22 at 17:23
  • 1
    Try to use `@RequestBody String request` and make sure you backend receive correct json – talex Nov 16 '22 at 17:37
  • @talex I tried this, and the json seems to be received correctly, so the issue would come from the json parser or the creation of a new object... – Thibaut B. Nov 16 '22 at 17:51

2 Answers2

0

There is a small issue in your CURL request. No need to use an escape character with "key". You are using a backslash with double quotes (\") that is not required.

Please try this CURL request.

curl --request POST --header "Content-Type: application/json" --data '{"key": 5}' http://localhost:8080/request
Rohit Agarwal
  • 763
  • 2
  • 5
  • 10
0

Some only CURL will not work we need to mention in below format:

curl.exe --request POST --header "Content-Type: application/json" --data '{"key": 5}' http://localhost:8080/request