【问题标题】:JSON schema validation while executing POST request and reading POST data entered by user using spring boot rest api执行 POST 请求并读取用户使用 Spring Boot Rest api 输入的 POST 数据时的 JSON 模式验证
【发布时间】:2020-10-11 01:25:24
【问题描述】:

如何在 POST 请求中使用指定的模式 验证(使用指定的模式)用户的 JSON 输入(我们必须每次验证 JSON 数据是通过 POST 请求接收的)?另外,如何从发布请求中实际提取用户输入的数据?我做了以下操作来提取输入我的用户的数据

@PostMapping("/all-configs")
public Animal createConfig( @RequestBody Animal ani) {
try {
    System.out.println(ani);//output: net.company.sprinboot.model.Animal@110e19d9
    System.out.println(ani.toString());//output: net.company.sprinboot.model.Animal@110e19d9
    String str = ani.toString();
    System.out.println(str);//output: net.company.sprinboot.model.Animal@110e19d9
} … … …. .. . ...etc

请帮忙!如何才能真正读取用户在 post 请求中输入的 JSON 数据?

【问题讨论】:

    标签: java json spring-boot post json-schema-validator


    【解决方案1】:

    如何在 POST 请求期间使用 指定的模式(我们必须每次验证 JSON 数据 通过 POST 请求接收)?

    添加注解@Valid(来自javax.validation.valid),像这样:

    public Animal createConfig(@Valid @RequestBody Animal ani) {
    

    在您的 Animal DTO 上,在要验证的字段上添加注释,例如:

    public class Animal implements Serializable {
        ...
    
        @Size(max = 10)
        @NotBlank
        private String name;
    
        ... 
    }
    

    当 Spring Boot 找到一个带有 @Valid 注释的参数时,它会引导 Hibernate Validator(JSR 380 实现)并要求它执行 bean 验证。

    当验证失败时,Spring Boot 会抛出 MethodArgumentNotValidException

    另外,如何从帖子中实际提取用户输入的数据 请求?

    在 Animal POJO 上使用 getter 方法。示例:

    String name = ani.getName();
    



    更新:

    另外,如果我有这样的 json:{"hype": {"key1":"value1"} }... 那么如何 我可以访问 hype.key1 中的 value1 吗?

    @RestController
    public class Main {
        @PostMapping("/all-configs")
        public void createConfig(@Valid @RequestBody Animal ani) {
            Map<String, String> hype = ani.getHype();
            System.out.println(hype.get("key1"));
        }
    }
    
    public class Animal implements Serializable {
        private Map<String, String> hype;
    
        public Map<String, String> getHype() {
            return hype;
        }
    
        public void setHype(Map<String, String> hype) {
            this.hype = hype;
        }
    }
    

    输出:

    值1

    【讨论】:

    • 感谢您的回复@jumping_monkey。另外,如果我有一个像这样的 json:{"hype": {"key1":"value1"} }... 那么我如何访问 hype.key1 中的 value1?
    • 嗨 @jumping_monkey ,对 stackoverflow.com/questions/62921359/… 有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 2019-11-06
    • 2013-08-22
    • 1970-01-01
    • 2018-10-14
    • 2017-05-22
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多