1

I have a controller in my application that accepts logs. When I send an empty json object ('{}') or valid requests but with one or more empty fields, it is automatically deserialised into an empty LogDTO object or a LogDTO with a field set to 0 (for numerical fields). I want to reject requests with empty fields.

My controller:

@PostMapping("new/log")
public ResponseEntity<Log> newLog(@Valid @RequestBody LogDTO logDTO) {
    return new ResponseEntity<>(logService.newLog(logDTO), HttpStatus.OK);
}

LogDTO object:

public class LogDTO {

/**
 * The date and time for this specific log, in miliseconds since epoch.
 */
@Min(0)
@NotNull
@JsonInclude(JsonInclude.Include.NON_NULL)
private long epochDate;

/**
 * The heartRate per minute for this specific time.
 */
@Min(0)
@NotNull
@JsonInclude(JsonInclude.Include.NON_NULL)
private int heartRate;

/**
 * The user this log belongs to.
 */
@Min(0)
@NotNull
@JsonInclude(JsonInclude.Include.NON_NULL)
private long userId;

/**
 * The night this log belongs to. Every sleepsession represents one night.
 */
@Min(0)
@NotNull
@JsonInclude(JsonInclude.Include.NON_NULL)
private long sleepSession;

public LogDTO() {
}

public LogDTO(long epochDate, int heartRate, long userId, long sleepSession) {
    this.epochDate = epochDate;
    this.heartRate = heartRate;
    this.userId = userId;
    this.sleepSession = sleepSession;
}
//getters and setters

I tried setting 'spring.jackson.default-property-inclusion=non-default' in my application properties too, but it kept setting the fields to '0'. Is there any way I can either set empty fields to 'null' instead of '0', or reject the object in validation?

TheDokter
  • 23
  • 2
  • 2
    Can you change to Wrapper types instead of primitives? Integer instead of int and Long instead of long – Tushar Nov 30 '20 at 15:27
  • Take a look on this: [Jackson @JsonProperty(required=true) doesn't throw an exception](https://stackoverflow.com/questions/18320731/jackson-jsonpropertyrequired-true-doesnt-throw-an-exception) – Michał Ziober Nov 30 '20 at 20:59
  • @Tushar I could, with some refactoring. What would that change for me? – TheDokter Nov 30 '20 at 22:05
  • When you use primitives it is defaulted to zero instead of null. I tried and with Wrapper type you get a validation exception. – Tushar Dec 01 '20 at 09:14
  • 1
    @Tushar thank you, this worked. – TheDokter Dec 01 '20 at 14:08

1 Answers1

0

As @Tushar mentioned in the comments, changing my types in my LogDTO object from primitive types to wrappers solved my issue.

TheDokter
  • 23
  • 2