Home > front end >  Json View doesn't restrict the fields in the response
Json View doesn't restrict the fields in the response

Time:05-19

I need to send only 1 field annotated with @JsonView(in my case : eNumber) in my response. Also, this has to be only when the call is from Controller1 which also has a JsonView annotation. But, eNumber field value is sent also when the call is from Controller2 which is not annotated with @JsonView. What am I missing here ?

Below is my code:

DTO:

public class MyClass {

    @JsonView(Views.InternalRequest.class)
    public String getEnumber() {        
      
      return eNumber;
    }
    
    .... other fields
}

Controller classes :

@RequestMapping("/api/ctr")
public class Controller1 {
    
    @GetMapping(value = "/{serviceId}/eva", produces = MediaType.APPLICATION_JSON_VALUE)
    @JsonView(Views.InternalRequest.class)
    public ResponseEntity<MyClass> findAllEva() {
    
        return ResponseEntity.ok(new MyClass());
    }
}

@RequestMapping("/api/abcd")
public class Controller2 {
    
    @GetMapping(value = "/{serviceId}/evss", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MyClass> findAllEvs() {
    
        return ResponseEntity.ok(new MyClass());
    }
}

View:

public class Views {
    public static class InternalRequest {
    }
}

CodePudding user response:

I believe you need to do the following:

  1. Define two views; one for internal one for public.
  2. Annotate the fields not the getters (I believe, not 100% sure about this step).
  3. Annotate the Controller2 method with "@JsonView(Views.Public.class)"

Here is a Baeldung article describing JsonViews

  • Related