1

Two types of POST requests are sent to the "/numbers" endpoint:

{
    "type": "A",
    "numberOne": 1
}

and

{
    "type": "B",
    "numberOne": 1,
    "numberTwo": 2
}

How to validate for type A that numberOne is not null and for type B that numberOne and numberTwo are not null? I was able to find explanations of how to achieve this with two different endpoints and validation groups, but not how to achieve this with one endpoint.

@RestController
public class NumbersController {

    @PostMapping("/numbers")
    public Numbers addNumbers(@Valid @RequestBody Numbers numbers) {
        // Create data. 
        return numbers;
    }
}

@Data
public class Numbers {
    private String type;
    @NotNull
    private Integer numberOne;
    @NotNull
    private Integer numberTwo;
}

Anne Maier
  • 299
  • 1
  • 8
  • You need a polymoprhic JSON deserializer. If you're using Jackson (you seem to, the default JSON deserializer for a Spring MVC application), then https://stackoverflow.com/questions/30362446/deserialize-json-with-jackson-into-polymorphic-types-a-complete-example-is-giv can help you. Also make sure you have `ObjectMapper` properly configured. Note that using polymorphic objects can be very hard to maintain in the future, so you can consider using distinct endpoints unless it's a real "no-no". – terrorrussia-keeps-killing May 02 '22 at 13:40

0 Answers0