0

I have the following REST API:

@ResponseBody
    @PostMapping(path = "/configureSegment")
    public ResponseEntity<ResultData> configureSegment(@RequestParam() String segment,
                                                       @RequestBody @Valid CloudSegmentConfig segmentConfig
                                                        )  {

CloudSegmentConfig:

@JsonProperty(value="txConfig", required = true)
    @NotNull(message="Please provide a valid txConfig")
    TelemetryConfig telemetryConfig;
    @JsonProperty(value="rxConfig")
    ExternalSourcePpdkConfig externalSourcePpdkConfig = new ExternalSourcePpdkConfig(true);

TelemetryConfig:

public class TelemetryConfig {

    static Gson gson = new Gson();

    @JsonProperty(value="location", required = true)
    @Valid
    @NotNull(message="Please provide a valid location")
    Location location;

    @Valid
    @JsonProperty(value="isEnabled", required = true)
    @NotNull(message="Please provide a valid isEnabled")
    Boolean isEnabled;

Location:

static public enum Location {
        US("usa"),
        EU("europe"),
        CANADA("canada"),
        ASIA("asia");
        private String name;

        private Location(String s) {
            this.name = s;
        }
        private String getName() {
            return this.name;
        }
    }

When I'm trying to send the following JSON:

{
    "txConfig": {
        "location": "asdsad"
    }
}

The API return empty response 400 bad request, while I expect it to validate the location to be one of the ENUMs of the class. I also expect it to validate the isEnable parameter while it doesn't although I added all possible annotation to it..

Any idea?

TheUnreal
  • 23,434
  • 46
  • 157
  • 277

1 Answers1

0

Use @Valid annotation on TelemetryConfig telemetryConfig and no need to use @Valid on the field of TelemetryConfig class.

@Valid
TelemetryConfig telemetryConfig;

And for enum subset validation you can create a customer validator with annotation and use it. A good doc about this Validating a Subset of an Enum

Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • Thanks! I see that the errors are showing the real class name instead of the Jackson name, e.g `"telemetryConfig.isEnabled: Please provide a valid isEnabled",` instead of `txConfig`, any way to solve that? – TheUnreal May 06 '20 at 12:05
  • Maybe you are looking some this https://stackoverflow.com/questions/41717866/jsr-303-validation-in-spring-controller-and-getting-jsonproperty-name – Eklavya May 06 '20 at 12:12