Spring Boot: Dynamically Ignore Fields While Serializing Java Objects to JSON

Let’s say that we have a UserController class with two GET endpoints:

  • /users/{id} endpoint, which returns a User object for a given id
  • /users endpoint, which returns List<User>
Java

 

xxxxxxxxxx
1

26

1

public class User {

2


3

    private Integer id;

4

    private String name;

5

    private Date dateOfBirth;

6

    private String city;

7

    

8

    // constructors, getters & setters are ignored

9

}

10


11

@RestController

12

public class UserController {

13

    

14

    @Autowired

15

    UserService userService;

16

    

17

    @RequestMapping(value = "/user/{id}", method= RequestMethod.GET)

18

    User getUser(@PathVariable("id") String id){

19

        return userService.getUser(id);

20

   }

21

    

22

    @RequestMapping(value = "/users", method= RequestMethod.GET)

23

    List<User> getAllUsers(){

24

        return userService.getAllUsers();

25

   }

26

}

Source de l’article sur DZONE