Posts

Showing posts from September, 2018

Conditional field inclusion in Jackson and Spring Boot

When we write JSON API with spring boot, we often need to customize which fields should be included in our response JSON and which should not. For example, suppose we've a Model like the following: public class User {     private Long id;     private String name;     private String password;     private List<String> children;     // getters and setters here } Now we've the following controller: @RestController @RequestMapping("/api/users") public class UserController {     @GetMapping     public List<User> userList(){         User user = new User();         user.setId(10L);         user.setName("Rafiqunnabi Nayan");         user.setPassword("abcd");         user.setChildren(Arrays.asList("Child 1", "Child 2"));         return Arrays.asList(user);     }     @GetMapping("{id}")     public User userDetails(@PathVariable Long id){         User user = new User();         user.set