[英]Jackson converting java object primitive properties as optional in json string
我是 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 请求数据创建请求对象的方法。 谢谢。
userId
和type
是原始type
的int
,默认值为0
并且JsonInclude.Include.NON_NULL
只会忽略具有 null 值的属性,因此将userId
和type
设为Integer
类型,使其默认值为null
,jackson 可以排除它们
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReportRequest {
@NotNull
private String startDate;
@NotNull
private String endDate;
private Integer userId;
private Integer type;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.