不需要自定义验证器。有一种方法可以告诉杰克逊投掷
您只需要添加或自定义构造函数。像这样的东西应该工作:@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"])