【问题标题】:Jackson converting java object primitive properties as optional in json stringJackson 将 java 对象原始属性转换为 json 字符串中的可选属性
【发布时间】: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


【解决方案1】:

userIdtypeint 的原始值,默认值为 0JsonInclude.Include.NON_NULL 只会忽略具有空值的属性,因此将 userIdtype 设置为 @987654328 @type 使其默认值为null,jackson 可以排除它们

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

  @NotNull
  private String startDate;

  @NotNull
  private String endDate;

  private Integer userId;

  private Integer type;

 }

【讨论】:

  • 非常感谢您的快速回复。我按照你的建议做了,效果很好。
猜你喜欢
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2015-04-14
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多