JSON 在执行 POST 请求和读取 POST 用户使用 spring 启动休息 api 输入的数据时进行模式验证

JSON schema validation while executing POST request and reading POST data entered by user using spring boot rest api

如何在使用指定模式的 POST 请求期间验证(使用指定模式)用户的 JSON 输入 (我们必须在每次通过 POST 请求接收到数据时验证 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 数据?

How to validate a JSON input by user during a POST request using a specified schema (we have to validate the JSON data each time it is received through the POST request)?

添加注解@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 启动抛出 MethodArgumentNotValidException.

Also, how to actually extract data entered by the user form a post request?

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

String name = ani.getName();



更新:

Also, if I have a json like: {"hype": {"key1":"value1"} }… then how can I access value1 in hype.key1?

@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;
    }
}

输出:

value1