首页 > 解决方案 > 执行 POST 请求并读取用户使用 Spring Boot Rest api 输入的 POST 数据时的 JSON 模式验证

问题描述

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

@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

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

标签: javajsonspring-bootpostjson-schema-validator

解决方案


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

添加注释@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


推荐阅读