Java 8 jackson 验证

标签 java json spring spring-mvc jackson

我有一个 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"
} 

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

我在 Controller 中调用了这个 validator :

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

最佳答案

不需要自定义 validator 。有办法告诉 jackson 扔

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

关于Java 8 jackson 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36357713/

相关文章:

java - 如何从列表中选择以小写字母开头的字符串

java - 卡在 socket.accept()

arrays - SQL Server 2016 JSON : Select array of strings instead of array of objects

java - pom.xml 文件没有配置好

java - Spring Batch如何分块读取?它维护光标吗?

java - 修改InputStream并将其转换为Outputstream

java - Google Cloud Datastore 中的二维数组对象

json - 如何在输入时跳过 Struct 中的 JSON 字段并在输出中显示它们,以及在输入中接受某些字段并在 Golang 中在输出中跳过它们?

Python + Postgres + psycopg2 : Composing a dynamic json query and dealing with quotes

spring - 返回 Http 状态(例如 401)或重定向 Spring Security