Conditional @JsonView within controller method

968 views Asked by At

I have a controller method annotated with @JsonView. The current requirement is to have this same method return the response using a different JsonView if the userId given in parameter matches the authenticated user. How to achieve this knowing that response type should remain ResponseEntity<MyObject> and should not be changed to MappingJacksonValue or the sorts.

I'm using Spring, so maybe a way to do this is to have the default JacksonMapper injected and change its SerializationView depending on a condition within the method. But the question here is, what to inject and how to achieve this?

// Some controller annotations
@JsonView(Views.Public.class)
public static ResponseEntity<User> getUser(@PathVariable String userId)
    User user = userService.getUser(userId);
    User authenticated = userService.getAuthenticatedUser();
    if (userId.equals(authenticated.getId())) {
       // Change the view class to Views.Restricted.class
    }
    return new ResponseEntity<>(user, HttpStatus.OK);
}
1

There are 1 answers

1
khazouss On

Solved it by Injecting the spring default ObjectMapper and changing its config with the appropriate View class:

@Autowired
private ObjectMapper defaultMapper;
//...
public static ResponseEntity<User> getUser(@PathVariable String userId)
   User user = userService.getUser(userId);
   User authenticated = userService.getAuthenticatedUser();
   if (userId.equals(authenticated.getId())) {
      defaultMapper.setConfig(defaultMapper.getSerializationConfig().withView(Views.Restricted.class));
   } else {
      defaultMapper.setConfig(defaultMapper.getSerializationConfig().withView(Views.Public.class));
   }
   return new ResponseEntity<>(user, HttpStatus.OK);
}