Jackson将Java对象转换为带有可选数据的JSON字符串

问题描述 投票:1回答:1

我是Spring Boot的新手,我想向第3方API发送请求。我在JSON中具有以下发布参数,可以用作@ RequestBody;

{“ startDate”:“ 2015-07-01”,“ endDate”:“ 2015-10-01”,“ userId”:1“类型”:1}

OR

{“ startDate”:“ 2015-07-01”,“ endDate”:“ 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。对象。@PostMapping(value="/getData", produces = "application/json") public ResponseEntity getReport(@Valid @RequestBody ReportRequest reportRequest){ 当我发送带有所有JSON属性的请求时,没有问题。但是,当我仅发送强制性数据时,“ userId”和“ type”会自动设置为0。

我知道使用

Optional

不是最佳实践。我无法弄清楚使用2个可选JSON请求数据创建请求对象的方法。谢谢。

我是Spring Boot的新手,我想向第3方API发送请求。我在JSON中有以下发布参数,可用作@RequestBody; {“ startDate”:“ 2015-07-01”,“ ...

userIdtype是原始的int,默认值为0JsonInclude.Include.NON_NULL仅忽略具有空值的属性,因此将userIdtype设置为Integer输入,使其默认值为null,杰克逊可以排除它们
@JsonInclude(JsonInclude.Include.NON_NULL) public class ReportRequest { @NotNull private String startDate; @NotNull private String endDate; private Integer userId; private Integer type; }
java json spring spring-boot jackson
1个回答
2
投票
© www.soinside.com 2019 - 2024. All rights reserved.