如何在 spring 引导 REST API 中将空值包含到 JSON 响应

How to include null values to JSON responses in spring boot REST API

我正在开发 RESTful API。我想通过调用 API 获取用户详细信息。但是我预期的响应不包括空值。

预期响应

{
    "id": 1,
    "username": "admin",
    "fullName": "Geeth Gamage",
    "userRole": "ADMIN",
    "empNo": null
} 

实际响应

  {
        "id": 1,
        "username": "admin",
        "fullName": "Geeth Gamage",
        "userRole": "ADMIN"
    } 

我的 Spring 启动休息 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实体class和UserDTO对象class如下

User.class

@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;
}

UserDTO.class

@Data
public class  UserDTO {
    private Long id;
    private String username;
    private String fullName;
    private String userRole;
    private String empNo;
}

假设您使用的是 Jackson,您可以在 ObjectMapper.

上使用 setSerializationInclusion(JsonInclude.Include) 配置其 全局 行为

对于您的用例,您可以将其配置为 NON_EMPTYALWAYS。更多详情请查看https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonInclude.Include.html.

您也可以在 class 或属性级别 使用相应的注释 @JsonInclude.

执行此操作