Spring Boot @RequestBody bind null values to a default value?

Viewed 1721

I have a Spring Boot service that uses a custom POJO class for a POST request body. When client passes one of the fields as null, I would like that value to be set to 0.

@Data
public class CardAnswer {
    private Integer answerId = 0; //should always be 0 and never set to null
    private String value;
}

Used by the following controller:

@RequestMapping(value = "/{category}", method = RequestMethod.POST)
    public SalesPulseMResponse updateSecurity(@PathVariable(value = SalesedgeConstants.CATEGORY)
                                              @RequestBody CardAnswer requestBody) {

        return fooService.updateFieldsByCategory(category, requestBody);
    }

Spring boot will handle the data binding from JSON to the CardAnswer for me, but whenever answerId is passed as null, I want it to retain 0. Is there a proper way to do that or would I have to parse through the class and set the values myself? Currently, if the client doesn't pass in this field in their request JSON, it will retain the default value, however, I want that default value to be retained even for null values that were passed in.

2 Answers

ints have this property, so:

@Data
public class CardAnswer {
    private int answerId;
    private String value;
}

Example:

@Data
public class CounterRequest {
    private final int int1;
    private final int int2;
}

@Data
public class CounterResult {
    private final int value;
}

@RestController
@RequestMapping(
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
        consumes = MediaType.APPLICATION_JSON_VALUE)
public class CounterRestController {
    public static final String ADD_URL = "/counter/add";
    
    @RequestMapping(value = ADD_URL,
            method = RequestMethod.POST)
    public CounterResult add(@RequestBody @Valid
            CounterRequest counterRequest) {
        return new CounterResult(counterRequest.getInt1() + counterRequest.getInt2());
    }
}

Run:

$ curl -X POST -H "Content-Type: application/json"  --data "{\"int1\":null,\"int2\":2}" localhost:8080/counter/add
{"value":2}
$ curl -X POST -H "Content-Type: application/json"  --data "{\"int1\":1,\"int2\":2}" localhost:8080/counter/add
{"value":3}

You can use @JsonIgnore

@Data
public class CardAnswer {
    @JsonIgnore
    private Integer answerId = 0;
    private String value;
}
Related