首页 > 解决方案 > 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?

我想区分这两个请求

标签: javajsonspringserializationjackson

解决方案


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

推荐阅读