java - 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 请求数据创建请求对象的方法。谢谢。
解决方案
userId
and type
are是原始的int
,默认值 is0
并且JsonInclude.Include.NON_NULL
只会忽略具有空值的属性,因此 makeuserId
和type
asInteger
类型使其默认值 isnull
并且 jackson 可以排除它们
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReportRequest {
@NotNull
private String startDate;
@NotNull
private String endDate;
private Integer userId;
private Integer type;
}
推荐阅读
- python - matplotlib 的奇怪线条行为
- python - 在 Django 中使用内置的重置密码和密码更改时如何显示错误消息
- internationalization - wxPython 提供假文件翻译
- angular - 用于 TS/Angular 的键入继电器连接模型
- firebase - How to create multiple maps under the same array
- spring - 带有 Spring-Data-JPA 的 BLOB 类型
- node.js - 在 GET 请求中传递查询字符串,express 将查询字符串中的“+”字符转换为空格。如何避免这种情况?
- corda - Corda:受阻令牌可能存在延迟问题
- node.js - 错误:抱歉,将 Node 项目从 Windows 转移到 Debian 时客户端已经太多了
- php - 在 PHP 中提交简单表单时得到失败的结果