json - 如何在 Spring Boot REST API 中将空值包含到 JSON 响应中
问题描述
我正在开发一个 RESTful API。我想通过调用 API 来获取用户详细信息。但我的预期响应不包括空值。
预期响应
{
"id": 1,
"username": "admin",
"fullName": "Geeth Gamage",
"userRole": "ADMIN",
"empNo": null
}
实际反应
{
"id": 1,
"username": "admin",
"fullName": "Geeth Gamage",
"userRole": "ADMIN"
}
我的 Spring Boot Rest API 代码如下。为什么我的响应中不包含空参数?
@GetMapping(value = "/{userCode}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> findUser(@PathVariable String userCode)
{
return ResponseEntity.status(HttpStatus.OK).body(userService.getUserByUserName(userCode));
}
@Override
@Transactional
public Object getUserByUserName(String username)
{
try {
User user = Optional.ofNullable(userRepository.findByUsername(username))
.orElseThrow(() -> new ObjectNotFoundException("User Not Found"));
return new ModelMapper().map(user, UserDTO.class);
} catch (ObjectNotFoundException ex) {
log.error("Exception : ", ex);
throw ex;
} catch (Exception ex) {
log.error("Exception : ", ex);
throw ex;
}
}
User
实体类和UserDTO
对象类如下
用户类
@Data
@Entity
@Table(name = "user")
public class User{
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
private Long id;
@Column(name = "USERNAME", nullable = false, length = 64)
private String username;
@Column(name = "USER_ROLE", nullable = false)
private String userRole;
@Column(name = "EMP_NO")
private String empNo;
}
用户DTO.class
@Data
public class UserDTO {
private Long id;
private String username;
private String fullName;
private String userRole;
private String empNo;
}
解决方案
假设您使用的是 Jackson,您可以使用setSerializationInclusion(JsonInclude.Include)
.ObjectMapper
对于您的用例,您可以将其配置为NON_EMPTY或ALWAYS。有关更多详细信息,请查看https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonInclude.Include.html。
您也可以使用相应的注释在类或属性级别@JsonInclude
执行此操作。
推荐阅读
- mongodb - 如何使用保存命令停止 mongodb 中的重复数据
- javascript - 加载页面内容而不重新加载整个页面
- r - 运行库(ggplot2)时如何解决错误?
- javascript - 如何将 Jquery.canvascrop 裁剪图像上传到数据库
- php - Wordpress 在博客页面上显示私人和公共帖子
- amazon-web-services - 是否有任何替代方法可以增加 aws lambda 调用时间或管道结果
- php - wordpress 上传主题 您关注的链接已过期。(已经 set_time 限制 400 )
- android - 从存储和回收视图列表中删除选定的文件
- javascript - DOM 中的节点发生变化的事件顺序是什么?
- python - 为什么它不包含我的附加列表?我试图在循环时继续向列表中添加更多项目,但是当循环继续时它消失了