簡體   English   中英

忽略 spring 引導 api 請求正文中的空字段

[英]Ignoring empty fields in spring boot api requestbody

我的應用程序中有一個 controller 接受日志。 當我發送一個空的 json object('{}')或有效請求但具有一個或多個空字段時,它會自動反序列化為一個空的 LogDTO object(對於數字字段)。 我想拒絕帶有空字段的請求。

我的 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

我也嘗試在我的應用程序屬性中設置“spring.jackson.default-property-inclusion=non-default”,但它一直將字段設置為“0”。 有什么辦法可以將空字段設置為“null”而不是“0”,或者在驗證中拒絕 object?

正如@Tushar 在評論中提到的那樣,將我的 LogDTO object 中的類型從原始類型更改為包裝器解決了我的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM