1 回答
TA贡献1866条经验 获得超5个赞
在这种情况下,您应该定义POJO
类,并将属性设置为预定义undefined like
数据。例如,对于Integer
财产,如果从商业角度来看不允许使用负数,则可能是-1
。然后,当JSON
反序列化为设置POJO
为覆盖默认值的属性时null
,您就会知道它已发送。应该有3个选项:
常规值 in
JSON
- 正确反序列化为值 inPOJO
null
值 inJSON
- 反序列化为null
inPOJO
不可用对
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.
添加回答
举报