|
| 1 | +package com.apifiltering.RestAPIFiltering.controller; |
| 2 | + |
| 3 | +import com.apifiltering.RestAPIFiltering.entity.Student; |
| 4 | +import com.fasterxml.jackson.databind.ser.FilterProvider; |
| 5 | +import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; |
| 6 | +import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; |
| 7 | +import org.springframework.http.converter.json.MappingJacksonValue; |
| 8 | +import org.springframework.web.bind.annotation.GetMapping; |
| 9 | +import org.springframework.web.bind.annotation.RestController; |
| 10 | + |
| 11 | +import java.util.Arrays; |
| 12 | +import java.util.List; |
| 13 | + |
| 14 | +@RestController |
| 15 | +public class FilteringController { |
| 16 | + |
| 17 | + @GetMapping("/filtering") |
| 18 | + public MappingJacksonValue filtering() { |
| 19 | + // Create a Student object with all fields populated |
| 20 | + Student student = new Student("Paras Bagga", "Gurgaon", "8437861802"); |
| 21 | + // Apply dynamic filtering to include only 'name' and 'city' properties |
| 22 | + return applyFiltering(student, "name", "city"); |
| 23 | + } |
| 24 | + |
| 25 | + @GetMapping("/filtering-list") |
| 26 | + public MappingJacksonValue filteringList() { |
| 27 | + // Create a list of Student objects |
| 28 | + List<Student> list = Arrays.asList( |
| 29 | + new Student("Paras Bagga", "Gurgaon", "8437861802"), |
| 30 | + new Student("Twinkle Mahajan", "Amritsar", "9000001234"), |
| 31 | + new Student("Aarushi Mahajan", "Gurgaon", "9999991234") |
| 32 | + ); |
| 33 | + // Apply dynamic filtering to include only 'name' and 'mobile' properties |
| 34 | + return applyFiltering(list, "name", "mobile"); |
| 35 | + } |
| 36 | + |
| 37 | + // Dynamic Filtering |
| 38 | + private MappingJacksonValue applyFiltering(Object object, String... properties) { |
| 39 | + MappingJacksonValue jacksonValue = new MappingJacksonValue(object); |
| 40 | + // Create a filter that only includes the specified properties |
| 41 | + SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept(properties); |
| 42 | + // Create a FilterProvider that adds the filter for the "StudentFilter" |
| 43 | + FilterProvider filters = new SimpleFilterProvider().addFilter("StudentFilter", filter); |
| 44 | + // Create a FilterProvider that adds the filter for the "StudentFilter" |
| 45 | + jacksonValue.setFilters(filters); |
| 46 | + return jacksonValue; |
| 47 | + } |
| 48 | +} |
0 commit comments