【问题标题】:Java 8 Jackson validationJava 8 杰克逊验证
【发布时间】:2016-07-21 08:12:24
【问题描述】:

我有一个 springboot 休息服务。用户传入一个 json 对象,该对象被反序列化到这个 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:

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

我想让所有这些字段都是必需的。提供任何更少或更多的东西都会引发异常。有没有办法告诉杰克逊在反序列化时验证输入?我试过@JsonProperty(required=true) 但这不起作用;显然来自here 和here 似乎JsonProperty 注释不受尊重。

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

@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 输入而言,最佳实践是什么?还是我已经以最新的方式在做?

【问题讨论】:

    标签: java json spring spring-mvc jackson


    【解决方案1】:

    在构造函数上使用@JsonCreator 注释和@JsonProperty 将起作用。检查此answer。

    public final class Request {
        private String id;
        private double code;
        private String name;
    
        @JsonCreator
        public Request(@JsonProperty(required = true) String id,
                       @JsonProperty(required = true) double code,
                       @JsonProperty(required = true) String name) {
            this.id = id;
            this.code = code;
            this.name = name;
        }
    
        public String getId() {
            return id;
        }
    
        public double getCode() {
            return code;
        }
    
        public String getName() {
            return name;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 Jackson 模式验证。创建一个 schema.json 并针对此架构验证每个传入的输入。点击此链接了解更多详情http://wilddiary.com/validate-json-against-schema-in-java/

      【讨论】:

        【解决方案3】:

        不需要自定义验证器。有办法告诉杰克逊扔

        • JsonMappingException 如果您没有必填字段

        • UnrecognizedPropertyException 如果你有额外的字段(UnrecognizedPropertyException 只是扩展 JsonMappingException)。

        您只需要添加@JsonCreator 或自定义构造函数。像这样的东西应该可以工作:

        public Request(@JsonProperty(value= "id", required = true)String id,
                       @JsonProperty(value= "code",required = true)double code,
                       @JsonProperty(value= "name",required = true)String name) {
            this.id = id;
            this.code = code;
            this.name = name;
        }
        

        完整演示:

        import com.fasterxml.jackson.annotation.JsonCreator;
        import com.fasterxml.jackson.annotation.JsonProperty;
        import com.fasterxml.jackson.databind.JsonMappingException;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import java.io.IOException;
        
        public class Main {
        
        public static void main(String[] args) throws IOException {
            test("{\"id\": \"123457896\",\"code\": 1,\"name\": \"test\"}");
            test("{\"id\": \"123457896\",\"name\": \"test\"}");
            test("{\"id\": \"123457896\",\"code\": 1, \"c\": 1,\"name\": \"test\"}");
        }
        
        public static void test(String json) throws IOException{
            ObjectMapper mapper = new ObjectMapper();
            try {
                Request deserialized = mapper.readValue(json, Request.class);
                System.out.println(deserialized);
                String serialized = mapper.writeValueAsString(deserialized);
                System.out.println(serialized);
            } catch (JsonMappingException e) {
                System.out.println(e.getMessage());
            }
        }
        
        public static class Request {
            private String id;
            private double code;
            private String name;
        
            public Request(@JsonProperty(value= "id", required = true)String id,
                           @JsonProperty(value= "code",required = true)double code,
                           @JsonProperty(value= "name",required = true)String name) {
                this.id = id;
                this.code = code;
                this.name = name;
            }
        
            public String getId() {
                return id;
            }
        
            public void setId(String id) {
                this.id = id;
            }
        
            public double getCode() {
                return code;
            }
        
            public void setCode(double code) {
                this.code = code;
            }
        
            public String getName() {
                return name;
            }
        
            public void setName(String name) {
                this.name = name;
            }
        
            @Override
            public String toString() {
                return "Request{" +
                        "id='" + id + '\'' +
                        ", code=" + code +
                        ", name='" + name + '\'' +
                        '}';
            }
        }
        }
        

        结果:

        Request{id='123457896', code=1.0, name='test'}
        {"id":"123457896","code":1.0,"name":"test"}
        Missing required creator property 'code' (index 1)
         at [Source: {"id": "123457896","name": "test"}; line: 1, column: 34]
        Unrecognized field "c" (class Main7$Request), not marked as ignorable (3 known properties: "id", "code", "name"])
         at [Source: {"id": "123457896","code": 1, "c": 1,"name": "test"}; line: 1, column: 53] (through reference chain: Request["c"])
        

        【讨论】:

        • 如果我想确保代码不为空或不为空怎么办。
        • 例如 test("{\"id\": \"123457896\",\"code\": 1,\"name\": \" "}") 为此我想要我的测试失败,因为名称为空但字段存在
        【解决方案4】:

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

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

        查看here的好例子

        【讨论】:

        • 使用这种技术,当验证失败时,如何像上面那样抛出我自己的自定义异常?
        • 您可以使用@ExceptionHandler注解来抛出异常并提供您想要的响应。类似的东西:@ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class, HttpRequestMethodNotSupportedException.class}) public ResponseEntity badRequest(HttpServletRequest request, Exception ex) {
        • 如何获取 Json 中不存在的所需字段名称?
        • 发现这是所有提到的最佳策略
        猜你喜欢
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-09
        • 2015-02-04
        • 2012-10-01
        • 2016-04-30
        相关资源
        最近更新 更多