首页 > 解决方案 > Springboot:可以在运行时更改DTO,而从api返回的对象中不存在空值吗?

问题描述

我有一个 springboot 应用程序,它正在访问数据源的原始 api。现在假设我有一个包含大约 50 个字段的客户实体,并且我有一个原始 api,我在其中传递列的名称并获取该列的值。现在我在springboot中实现api,它消耗原始api。

我需要在springboot中为客户实体的字段的不同组合实现不同的api,并且只返回用户查询过的对象中设置的那些字段,并从对象中删除空值字段。一种方法是为客户实体的列的不同组合实现不同的 dto。有没有其他方法可以实现相同的,我不需要为 Spring boot 中 Customer 实体的列的不同组合定义不同的 dto ???

标签: javaspringspring-bootentitydto

解决方案


您可以ObjectMapper直接配置,也可以使用@JsonInclude注解:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

OR

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Customer {

    private Long id;
    private String name;
    private String email;
    private String password;

    public Customer() {
    }

    // getter/setter ..
}

您可以使用此示例代码查看如何执行此操作:

Customer customer = new Customer();
customer.setId(1L);
customer.setName("Vikas");
customer.setEmail("info@vikas.com");

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String valueAsString = objectMapper.writeValueAsString(customer);

由于留下了密码null,您将拥有一个不存在密码的对象。

{
  "id": 1,
  "name": "Vikas",
  "email": "info@vikas.com"
}

推荐阅读