Java 8 杰克逊验证

新手上路,请多包涵

我有一个 springboot 休息服务。用户传入一个反序列化到这个 java pojo 中的 json 对象:

 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) 但这不起作用;显然从 这里这里 看来 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 输入方面的最佳实践是什么?还是我已经以最新的方式进行了?

原文由 Richard 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 426
2 个回答

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

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

这里 查看两者的好例子

原文由 Dennis R 发布,翻译遵循 CC BY-SA 3.0 许可协议

不需要自定义验证器。有一种方法可以告诉杰克逊投掷

  • 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"])

原文由 varren 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题