java - Springboot:可以在运行时更改DTO,而从api返回的对象中不存在空值吗?
问题描述
我有一个 springboot 应用程序,它正在访问数据源的原始 api。现在假设我有一个包含大约 50 个字段的客户实体,并且我有一个原始 api,我在其中传递列的名称并获取该列的值。现在我在springboot中实现api,它消耗原始api。
我需要在springboot中为客户实体的字段的不同组合实现不同的api,并且只返回用户查询过的对象中设置的那些字段,并从对象中删除空值字段。一种方法是为客户实体的列的不同组合实现不同的 dto。有没有其他方法可以实现相同的,我不需要为 Spring boot 中 Customer 实体的列的不同组合定义不同的 dto ???
解决方案
您可以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"
}
推荐阅读
- java - 是否可以在不声明多个扫描仪的情况下多次使用文件扫描仪?
- ssl - 更新letsencrypt SSL证书后,服务器只返回响应码400
- amazon-web-services - 如何使用 aws API Gateway 从具有多个定义的另一个模型中引用一个模型
- mongodb - Mongodb $mergeObjects 使用变量属性作为对象键
- python-3.x - 根据条件对excel中单元格内容部分着色的问题
- angular - 使用 Angular 查询在 Firestore 集合中组织我的数据以获得最佳性能
- javascript - 从 mongoose 唯一索引中捕获重复错误并发送 res 409
- node.js - 无法验证第一个证书离子 4
- vb.net - 使用 Access 数据库中的 URL 在 PictureBox 中显示图像
- javascript - 如何从此站点禁用鼠标滚轮