【问题标题】:Micronaut nested Json input ValidationMicronaut 嵌套 Json 输入验证
【发布时间】:2021-03-02 05:07:36
【问题描述】:

你如何验证 Json Body

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

这不起作用,它接受 JSON 正文中带或不带标记,即使 @NotNull 等被添加到学生 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;
    }
}

使用@Validated 注解的控制器 使用@Valid @Body 注释的方法参数

【问题讨论】:

    标签: java micronaut


    【解决方案1】:

    这在 Micronaut 版本 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;
        }
    }
    

    字段marks 应注释为:

    • @NotNull - 告诉验证者它必须存在
    • @Valid - 告诉验证器它必须验证嵌套字段

    示例控制器如下所示:

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

    通过 curl 测试:

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

    有了这个回复:

    {
      "message": "student.marks: must not be null",
      "_links": {
        "self": {
          "href": "/students",
          "templated": false
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多