Java 8 Jackson验证 [英] Java 8 Jackson validation

查看:682
本文介绍了Java 8 Jackson验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个springboot休息服务。用户传入一个json对象,该对象被反序列化为此java pojo:

I have a springboot rest service. The user passes in a json object that gets deserialized into this java pojo:

public final class Request {
    private String id;
    private double code;
    private String name;

    public String getId() {
        return id;
    }

    public double getCode() {
        return code;
    }

    public String getName() {
        return name;
    }
}

因此用户需要传入以下json:

So the user needs to pass in the following json:

{
    "id": "123457896",
    "code": "Foo",
    "name": "test"
} 

我想做所有的那些领域需要。提供更少或更多的东西会引发异常。有没有办法告诉杰克逊在反序列化时验证输入?我试过 @JsonProperty(required = true)但是这不起作用;显然来自这里这里似乎没有遵守 JsonProperty 注释。

I want to make all of those fields required. Providing anything less or more will throw an exception. Is there a way to tell jackson to validate the input when it deserializes? I've tried @JsonProperty(required=true) but this doesn't work; apparently from here and here it seems the JsonProperty annotation is not respected.

我在控制器中调用了这个验证器:

I have this validator that I call in my controller:

@Component
public class RequestValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }

    @Override
    public void validate(Object target, Errors errors) {
        String id = ((Request) target).getId();
        if(id == null || id.isEmpty()) {
            throw new InvalidRequestException("A valid id is missing. Please provide a non-empty or non-null id.");
        }
    }
}

但这似乎很乏味难以检查每个领域。所以鉴于我使用的是java 8,spring boot和jackson的最新版本,在验证传入的json输入方面,最佳做法是什么?或者我是否已经以最新方式进行此操作?

But that just seems tedious and ugly to check every field. So given I'm using java 8, spring boot and latest version of jackson what is the best practice in terms of validating an incoming json input? Or am I already doing it in the most up to date manner?

推荐答案

您使用了Spring Validator方法。
还有另一种方法:

You used Spring Validator approach. There is another approach:

J2EE JSR-303 / JSR-349 Bean Validation API。它提供了验证注释(javax,而不是jackson)。

J2EE JSR-303/JSR-349 Bean Validation API. it provides validation annotations (javax, not jackson).

查看两者的好例子这里

这篇关于Java 8 Jackson验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆