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
}



Serializable Java Lambdas

Recently I was presented with the following error when serializing a lambda with Kryo:

Java
 




x


 
1
com.esotericsoftware.kryo.KryoException: 
2
  java.lang.IllegalArgumentException: 
3
    Unable to serialize Java Lambda expression, unless explicitly declared e.g., 
4
    Runnable r = (Runnable & Serializable) () -> System.out.println("Hello world!");


If you do not recognize the (Runnable & Serializable) syntax, don’t worry, it is merely stating that the lambda must implement two types. This is called Type Intersection. Personally, I have never needed to use this myself, so have never really thought about it. Serializable is a bit of a unique interface in this regards, as there is nothing you actually need to implement.