简体   繁体   中英

Json to POJO null field

The service receives this JSON:

{
    "fieldA" : null
}

or this one:

{
    "fieldB" : null
}

The java class model is:

@Data
public class MyRequest implements Serializable {
    private Integer fieldA;
    private Integer fieldB;
}

The service is:

@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();
    ...
}

Here both a and b integers are null with both of requests.

Is there a way to know if the field was set to null in the json or if it was null because of not set?

I would like to make the difference between the 2 requests

You can choose any default value and treat it as a marker whether field was set or not. If field is set to default value it means there was no given field in JSON payload. Take a look at below example:

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);
    }
}

Above code prints:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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