【发布时间】:2020-02-23 21:01:20
【问题描述】:
我是 Spring Boot 的新手,我想向第 3 方 API 发送请求。我在 JSON 中有以下帖子参数用作 @RequestBody;
{ “开始日期”:“2015-07-01”, “结束日期”:“2015 年 10 月 1 日”, “用户ID”:1, “类型”:1, }
或
{ “开始日期”:“2015-07-01”, “结束日期”:“2015-10-01” }
public class ReportRequest {
@NotNull
private String startDate;
@NotNull
private String endDate;
private int userId;
private int type;
//getters and setters
我在类和字段级别使用 @JsonInclude(JsonInclude.Include.NON_EMPTY。我还尝试 NON_NULL 忽略“userId”和“类型”,但我仍然将它们放在@RequestBody 对象中。
@PostMapping(value="/getData", produces = "application/json")
public ResponseEntity getReport(@Valid @RequestBody ReportRequest reportRequest){
当我发送带有所有 JSON 属性的请求时没有问题。但是,当我只是发送强制数据时,'userId' 和 'type' 会自动设置为 0。
我知道使用 Optional 并不是最佳做法。我想不出用 2 个可选 JSON 请求数据创建请求对象的方法。谢谢。
【问题讨论】:
-
尝试使用
Integer而不是int
标签: java json spring spring-boot jackson