在JSON对象中强制执行非空字段 [英] Enforce not-null field in JSON object

查看:116
本文介绍了在JSON对象中强制执行非空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的REST API接收一些JSON对象输入,其中某些字段必须不为null。那些可以是String / Integer,甚至可能是其他类实例作为参考。

Our REST API recieves some JSON objects input where some fields are required to be not null. Those can be either String/Integer or even might be some other class instance as reference.

我们试图找到一种方法来强制那些字段不为null,而是在api中进行空检查的正确方法。
当前:

We are trying to find a way to enforce those field to be not null, instead of the corrent way for null check in the api. Current:



    if (myObject.getSomeOtherObject() == null)
    throw new SomeException();

我们想要的是:



    class MyObject{
    @Required
    OtherObject someOtherObject;
    ...
    }

我们尝试了3件事:

扩展JsonDeserializer以检查null但问题是它甚至没有在空输入上执行。

Extending JsonDeserializer to check null but the problem is that it does not even executed on the null input.



    public class NotNullDeserializer<T> extends JsonDeserializer<T> {

        @Override
        public T deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {

            ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
            Class type = (Class) superClass.getActualTypeArguments()[0];

            T t = jsonparser.readValueAs(type);

            if (t == null){
                String classNameField = type.getName();
                String field = jsonparser.getCurrentName();
                throw new WrongInputException("The field '"+field+"' of type '"+classNameField+"' should not be null.");
            }

            return t;
        }

    }

    public class NotNullAddressDeserializer extends NotNullDeserializer<Address> {

    }

    @JsonDeserialize(using=NotNullAddressDeserializer.class)
        Address to;




  • 编写我们自己的@Required注释并尝试检查ResourceFilter,但似乎我无法从ContainerRequest获取实际对象,即使我们可以,也不确定如何在object.otherObject.someObject.fieldNotNullable

  • 
    
        private class Filter implements ResourceFilter, ContainerRequestFilter {
    
            private final ArrayList requiredParameters;
    
            protected Filter() {
                requiredParameters = null;
            }
    
            protected Filter(ArrayList requiredParameters) {
                this.requiredParameters = requiredParameters;
            }
    
            @Override
            public ContainerRequestFilter getRequestFilter() {
                return this;
            }
    
            @Override
            public ContainerResponseFilter getResponseFilter() {
                return null;
            }
    
    
            @Override
            public ContainerRequest filter(ContainerRequest request) {
                if (requiredParameters != null && requiredParameters.size() > 0) {
                    MultivaluedMap params = request.getQueryParameters();
                    params.putAll(request.getFormParameters());
                    StringBuffer missingParams = new StringBuffer();
                    for (String reqParam : requiredParameters) {
                        List paramValues = params.get(reqParam);
                        if (paramValues == null || paramValues != null && paramValues.size() == 0)
                            missingParams.append(reqParam + ",");
                    }
                    if (missingParams.length() > 0)
                        throw new WrongInputException("Required parameters are missing: " + missingParams);
                }
                return request;
            }
        }
    
    



    任何帮助和见解表示赞赏。


    Any help and insights appreciated.

    推荐答案

    JAX-RS很好地将反序列化从验证中分离出来,即杰克逊有按设计否机制强制值非null 等。相反,您可以使用BeanValidation:

    JAX-RS separates quite nicely the deserialization from the validation, i.e. Jackson has by design no mechanism to enforce values to be non-null, etc. Instead, you can use BeanValidation for that:


    1. 提供范围内,向 javax.validation:validation-api 添加依赖项。

    2. javax.validation.constraints.NotNull 注释添加到您的字段中。

    1. Add a dependency to javax.validation:validation-api in provided scope.
    2. Add the javax.validation.constraints.NotNull annotation to your field.

    有关详细信息,请转到这里

    For more details, go here.

    这篇关于在JSON对象中强制执行非空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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