您可以在 JsonFilter 的帮助下实现这一点。
- 注释要过滤的类,如下所示:
@JsonFilter("employeeFilter")
public class Employee {
private String firstName ;
private String lastName ;
private String emailAddress ;
private String ssn ;
}
- 创建一个名为 FilterBeanService 的服务(或其他任何东西)
@Service
public class FilterBeanService {
// fields is an array of field names you wish not to sned in your response
// beanFilterName is value you give when you annotage your bean class
// dataSet is the data you want to filter
public static MappingJacksonValue filterBean(String[] fields, String beanFilterName, Object dataSet ) {
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept(fields);
FilterProvider filterProvider = new SimpleFilterProvider().addFilter(beanFilterName, filter);
MappingJacksonValue jacksonValue = new MappingJacksonValue(dataSet);
jacksonValue.setFilters(filterProvider);
return jacksonValue;
}
}
- 在您的控制器中,您可以过滤您不想要的文件
@GetMapping("/whatever")
public ResponseEntity<MappingJacksonValue> getSomething(){
List<Employee> employees = eventRepo.findAll();
String[] fields = {"ssn"};
MappingJacksonValue jacksonValue = FilterBeanService.filterBean(fields, "employeeFilter", employees);
return jacksonValue;
}