0

I've a simple Spring Boot application that has a single post method route that takes a request body and printing that body's property to console. This is my controller:

@RestController
@RequestMapping("v1")
public class ExampleController {
    @PostMapping("example")
    public ResponseEntity<String> example(@RequestBody ExampleBody body) {
        System.out.println(body.getBarcode());
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }
}

and this is the ExampleBody class

@Getter
@Setter
public class ExampleBody {

    @NonNull
    private String barcode;
}

I've expected that when I send a body with my request like that:

{
    "barcode": 1
}

it will fails, because I've declared that barcode as String in ExampleBody class.

However instead of throwing an exception, it passes and prints 1 to the console. I've checked the type of that 1 and it says that it is a java.lang.String. How am I gonna force that barcode to accept only strings?

  • 1
    You can only solve this by implementing your own Jackson deserializer. See the duplicates for more information about how to do this. Feel free to tag me when the duplicates do not answer your question so I can reopen it. – g00glen00b May 31 '23 at 13:01
  • 1
    Thank you @g00glen00b. Overriding the deserializer worked – Oğuz Öztınaz May 31 '23 at 18:02

0 Answers0