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:
- Define two views; one for internal one for public.
- Annotate the fields not the getters (I believe, not 100% sure about this step).
- Annotate the Controller2 method with "@JsonView(Views.Public.class)"
Here is a Baeldung article describing JsonViews