java - Json 到 POJO 空字段
问题描述
服务接收此 JSON:
{
"fieldA" : null
}
或者这个:
{
"fieldB" : null
}
java类模型是:
@Data
public class MyRequest implements Serializable {
private Integer fieldA;
private Integer fieldB;
}
服务是:
@PostMapping
@Produces({MediaType.APPLICATION_JSON})
@Consumes(value = {MediaType.APPLICATION_JSON})
public ResponseEntity<MyResponse> process(@RequestBody @Valid MyRequest request)
throws URISyntaxException {
Integer a = request.getFieldA();
Integer b = request.getFieldB();
...
}
这里 a 和 b 整数对于两个请求都是空的。
有没有办法知道该字段是否在 json 中设置为 null 或者是否因为未设置而为 null?
我想区分这两个请求
解决方案
您可以选择任何默认值并将其视为是否设置字段的标记。JSON
如果字段设置为默认值,则表示有效负载中没有给定字段。看看下面的例子:
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import java.io.IOException;
import java.io.Serializable;
public class JsonApp {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
MyRequest reqA = mapper.readValue("{\"fieldA\" : null}", MyRequest.class);
System.out.println(reqA);
System.out.println("Is fieldA set: " + reqA.isFieldASet());
System.out.println("Is fieldB set: " + reqA.isFieldBSet());
MyRequest reqB = mapper.readValue("{\"fieldB\" : null}", MyRequest.class);
System.out.println(reqB);
System.out.println("Is fieldA set: " + reqB.isFieldASet());
System.out.println("Is fieldB set: " + reqB.isFieldBSet());
}
}
@Data
class MyRequest implements Serializable {
private final Integer DEFAULT = Integer.MIN_VALUE;
private Integer fieldA = DEFAULT;
private Integer fieldB = DEFAULT;
public boolean isFieldASet() {
return !DEFAULT.equals(fieldA);
}
public boolean isFieldBSet() {
return !DEFAULT.equals(fieldB);
}
}
上面的代码打印:
MyRequest(DEFAULT=-2147483648, fieldA=null, fieldB=-2147483648)
Is fieldA set: true
Is fieldB set: false
MyRequest(DEFAULT=-2147483648, fieldA=-2147483648, fieldB=null)
Is fieldA set: false
Is fieldB set: true
推荐阅读
- visual-studio - 复制 XAML 文件时在代码中生成事件处理程序
- arrays - Excel - 数组上的 IFERROR 仅返回 ERROR
- websphere - IBM Process Center 用户角色仅用于部署
- ios - 新 iOS 应用的旧设备兼容性
- javascript - 为什么即使禁用缓存,服务器也会忽略代码文件中的更改?
- sql - 如何使这个 SQL 查询更短?
- javascript - 如何导入外部 .md 内容?
- json - 带有python jsonschema的未知url类型用于引用路径
- python - 时间序列数据中的 ValueError
- java - Webservice异常的潜在原因