【问题标题】:Json to POJO null fieldJson 到 POJO 空字段
【发布时间】:2021-08-22 07:19:22
【问题描述】:

服务接收这个 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?

我想在这 2 个请求之间做出区别

【问题讨论】:

  • 您可以在您想要的任何首选级别添加空检查。在您的端点类或 getter/setter 内部。您也可以使用验证罐。我假设您使用的是 lombok,因此有一个用于 null 处理的注释,即 NonNull。检查它是否适合您的场景。
  • 感谢您的建议,但 bith 字段为空,而一个在 json 中而不是另一个,我怎么知道一个在 json 中?

标签: java json spring serialization jackson


【解决方案1】:

您可以选择任何默认值并将其视为是否设置字段的标记。如果字段设置为默认值,则表示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

【讨论】:

  • 如果我没有忘记 no args 构造函数,那就完美了 :) 非常感谢
猜你喜欢
  • 1970-01-01
  • 2016-03-17
  • 2019-04-08
  • 2019-06-03
  • 2020-11-28
  • 1970-01-01
  • 2019-06-19
  • 2021-11-08
  • 2017-12-15
相关资源
最近更新 更多