首页 > 解决方案 > 如何在 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;
}

标签: jsonspringspring-bootresponserest

解决方案


假设您使用的是 Jackson,可以使用setSerializationInclusion(JsonInclude.Include).ObjectMapper

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

您也可以使用相应的注释在类或属性级别@JsonInclude执行此操作。


推荐阅读