3

Is is possible to exclude JsonProperties in the output of a Spring Boot Rest call based on a defined condition? (eg. the role of the user)

Example:

public class Employee{

    @JsonProperty
    private String name;
    @JsonProperty
    private String fieldForManagerOnly;
    @JsonProperty
    private String fieldForEmployeeOnly;

}

I want to have the fieldForManagerOnly only serialized in the JSON output when the user has the ROLE manager.

I've already tried the solution with the @JsonView (as described in Latest Jackson integration improvements in Spring) but that solution is very limited as the @JsonView is bound to one controler method and I want to have only one controller method.

Roman Cherepanov
  • 1,639
  • 2
  • 24
  • 44
userM1433372
  • 5,345
  • 35
  • 38

2 Answers2

9

I've solved the problem myself. I used the JsonView solution but instead of an annotation I select the JsonView from code.

First you need an interface for the Views.

public class JsonViews {

    public  interface EmployeeView {}
    public  interface ManagerView {}

}

Mark the fields in the Model class with the @JsonView annotations.

public class Employee{

    @JsonProperty
    private String name;

    @JsonView(JsonViews.ManagerView.class)
    private String fieldForManagerOnly;

    @JsonView(JsonViews.EmployeeView.class)
    private String fieldForEmployeeOnly;

}

In your controller set the JsonView to use based on the role (or some other condition):

@RequestMapping(value = "/{employeeId}", method = RequestMethod.GET)
public ResponseEntity<MappingJacksonValue> getEmployee(@PathVariable long employeeId) {
    Employee employee = employeeService.getEmployee(employeeId);
    MappingJacksonValue jacksonValue = new MappingJacksonValue(employeeResourceAssembler.toResource(employee));

    if (getRole().equals("MANAGER")) {
        jacksonValue.setSerializationView(JsonViews.ManagerView.class);
    } else if (getRole().equals("EMPLOYEE")) {
        jacksonValue.setSerializationView(JsonViews.EmployeeView.class);
    }

    return new ResponseEntity<>(jacksonValue, HttpStatus.OK);
}
userM1433372
  • 5,345
  • 35
  • 38
0

Annotate the field with

@JsonInclude(JsonInclude.Include.NON_NULL)

and make sure to set the field fieldForManagerOnly to null if the current user is not a manager.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255