5

How do you validate Json Body

{
  "name": "good student",
  "marks": {
    "math": "122",
    "english": "12"
  }
}

This Doesn't works, It accepts with or without marks in JSON body, even if @NotNull etc are added to marks in Student DTO

@Introspected
public @Data class Student {
    @NotBlank
    private String name;
    
    @Valid
    @JsonProperty("marks")
    private Marks marks;
    
    @Introspected
    static @Data class Marks{
        @NotBlank
        private String math;
        @NotBlank
        private String english;
    }
}

Controller Annotated with @Validated Method param annotated with @Valid @Body

Ayush Ghosh
  • 487
  • 2
  • 10

1 Answers1

4

This works for me in Micronaut version 2.0.3:

@Introspected
public @Data class Student {
    @NotBlank
    private String name;

    @Valid
    @NotNull
    private Marks marks;

    @Introspected
    static @Data class Marks{
        @NotBlank
        private String math;

        @NotBlank
        private String english;
    }
}

Field marks should be annotated by:

  • @NotNull - to tell the validator that it must be present
  • @Valid - to tell the validator that it must validate nested fields

Example controller looks like this:

@Validated
@Controller("/students")
public class StudentController {
    @Post
    public void create(@Valid @Body Student student) {
        // do something
    }
}

Tested by curl:

curl -v -X POST http://localhost:8080/students -H 'Content-Type: application/json' -d '{"name":"John"}' | jq

With this response:

{
  "message": "student.marks: must not be null",
  "_links": {
    "self": {
      "href": "/students",
      "templated": false
    }
  }
}
cgrim
  • 4,890
  • 1
  • 23
  • 42