0

I am using Jackson and spring boot. I have requirement to show/hide the filed from same response/request models based on controller. e.g. for controllerA i need to show the field and from controllerB i need hide it. The model being used is same in both the controller. I tried with @JsonView but its giving issues with Swagger documentation. Please help

  • Try using @JsonFilter, check this out - https://stackoverflow.com/questions/44032447/how-to-filter-attributes-from-json-response-in-spring. Let me know if that helps. – Mahesh_Loya Oct 24 '20 at 12:42

1 Answers1

0

You could use a custom annotation on a field ie: interface @PleaseIgnoreThis, include that on each field you want to treat differently then create a simple method using reflection to exclude those from the response.

entity:

MyEnity {

    @PleaseIgnoreThis
    long id = 123;

    String name = "the name";

    String attr = "some value"

}

annotation interface:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface PleaseIgnoreThis {}

example method:

Map<Object, Object> excludeTheseFromResponse(Object object) {
    Map<Object, Object>() map = new HashMap<>();
    for(Field f in object class) {
        if f does not have annotation PleaseIgnoreThis
            add it to the map (name, value)
    } 
    return map;
}

in the controller:

@RequestMapping(value="/somePath/{maybe_some_id})
Object getSomeEntity(id) {
    return myRepository.findById(id));
}

returns -> { "id": 123, "name": "the name", "attr": "some value" }

@RequestMapping(value="/somePath/{maybe_some_id})
Object getSomeEntity(id) {
    return excludeTheseFromResponse(myRepository.findById(id));
}

returns -> { "name": "the name", "attr": "some value" }

The annotation could include some extra value for granularity, and could be used to create finer control over how/what is included/excluded based on authorizations or location or time of day...