繁体   English   中英

Json 到 POJO null 字段

[英]Json to POJO null field

服务接收到这个 JSON:

{
    "fieldA" : null
}

或者这个:

{
    "fieldB" : null
}

java class model 是:

@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 整数都是 null 与两个请求。

有没有办法知道该字段是否在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM