心有法竹
在这种情况下,您应该定义POJO类,并将属性设置为预定义undefined like数据。例如,对于Integer财产,如果从商业角度来看不允许使用负数,则可能是-1。然后,当JSON反序列化为设置POJO为覆盖默认值的属性时null,您就会知道它已发送。应该有3个选项:常规值 in JSON- 正确反序列化为值 inPOJOnull值 in JSON- 反序列化为nullinPOJO不可用对key-value- 中的默认值POJO不会被覆盖。以下示例Jackson在版本中使用2.9.9:import com.fasterxml.jackson.annotation.JsonFormat;import com.fasterxml.jackson.annotation.JsonProperty;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;import java.time.LocalDateTime;public class JsonApp { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); String[] jsons = { "{\"number\":1,\"date\":\"2019-01-01T22:23:11\",\"max_amount\":4.9}", "{\"number\":null,\"date\":null,\"max_amount\":null}", "{}", "{\"number\":1}", "{\"date\":\"2019-01-01T22:23:11\"}", "{\"max_amount\":4.9}", "{\"number\":1,\"date\":null,\"max_amount\":null}" }; for (String json : jsons) { System.out.println(json + " => " + mapper.readValue(json, Pojo.class)); } }}class Pojo { private static final LocalDateTime NULL_DATE = LocalDateTime.of(1900, 1, 1, 12, 13); @JsonProperty("max_amount") private Double maxAmount = Double.MIN_VALUE; private Integer number = Integer.MIN_VALUE; @JsonFormat(shape = JsonFormat.Shape.STRING) private LocalDateTime date = NULL_DATE; public Double getMaxAmount() { return maxAmount; } public void setMaxAmount(Double maxAmount) { this.maxAmount = maxAmount; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public LocalDateTime getDate() { return date; } public void setDate(LocalDateTime date) { this.date = date; } @Override public String toString() { return "{" + "number=" + number + ", date=" + date + ", maxAmount=" + maxAmount + '}'; }}上面的代码打印:{"number":1,"date":"2019-01-01T22:23:11","max_amount":4.9} => {number=1, date=2019-01-01T22:23:11, maxAmount=4.9}{"number":null,"date":null,"max_amount":null} => {number=null, date=null, maxAmount=null}{} => {number=-2147483648, date=1900-01-01T12:13, maxAmount=4.9E-324}{"number":1} => {number=1, date=1900-01-01T12:13, maxAmount=4.9E-324}{"date":"2019-01-01T22:23:11"} => {number=-2147483648, date=2019-01-01T22:23:11, maxAmount=4.9E-324}{"max_amount":4.9} => {number=-2147483648, date=1900-01-01T12:13, maxAmount=4.9}{"number":1,"date":null,"max_amount":null} => {number=1, date=null, maxAmount=null}当然,您应该选择默认值,这样可以最大限度地减少客户端意外发送undefined您的API.