首页 > 解决方案 > Jackson 将 java 对象原始属性转换为 json 字符串中的可选属性

问题描述

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

{“startDate”:“2015-07-01”,“endDate”:“2015-10-01”,“userId”:1,“type”: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”和“type”,但我仍然在 @RequestBody 对象中有它们。

@PostMapping(value="/getData", produces = "application/json")
public ResponseEntity getReport(@Valid @RequestBody ReportRequest reportRequest){

当我发送带有所有 JSON 属性的请求时没有问题。但是,当我只发送强制数据时,“userId”和“type”会自动设置为 0。

我知道使用Optional不是最佳做法。我想不出用 2 个可选 JSON 请求数据创建请求对象的方法。谢谢。

标签: javajsonspringspring-bootjackson

解决方案


userIdand typeare是原始的int,默认值 is0并且JsonInclude.Include.NON_NULL只会忽略具有空值的属性,因此 makeuserIdtypeasInteger类型使其默认值 isnull并且 jackson 可以排除它们

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReportRequest {

  @NotNull
  private String startDate;

  @NotNull
  private String endDate;

  private Integer userId;

  private Integer type;

 }

推荐阅读