Spring MVC Ignore Json property for the given controller method

I have a Java class ( MyResponse ) that is returned by several RestController methods and has many fields.

 @RequestMapping(value = "offering", method=RequestMethod.POST) public ResponseEntity<MyResponse> postOffering(...) {} @RequestMapping(value = "someOtherMethod", method=RequestMethod.POST) public ResponseEntity<MyResponse> someOtherMethod(...) {} 

I want to ignore (for example, not serialize) one of the properties for only one method.

I do not want to ignore null fields for the class, because this can have a side effect for other fields.

 @JsonInclude(Include.NON_NULL) public class MyResponse { ... } 

JsonView looks good, but as I understand it, I have to comment out all the other fields in the class using @JsonView except the one I want to ignore, which sounds awkward. If there is a way to do something like "reverse JsonView", that would be great.

Any ideas on how to ignore a property for a controller method?

+5
source share
1 answer

Substitutes this guy.

By default (and in Spring Boot) MapperFeature.DEFAULT_VIEW_INCLUSION is enabled in Jackson. This means that all fields are enabled by default.

But if you annotate any field with a view different from the view on the controller method, this field will be ignored.

 public class View { public interface Default{} public interface Ignore{} } @JsonView(View.Default.class) //this method will ignore fields that are not annotated with View.Default @RequestMapping(value = "offering", method=RequestMethod.POST) public ResponseEntity<MyResponse> postOffering(...) {} //this method will serialize all fields @RequestMapping(value = "someOtherMethod", method=RequestMethod.POST) public ResponseEntity<MyResponse> someOtherMethod(...) {} public class MyResponse { @JsonView(View.Ignore.class) private String filed1; private String field2; } 
+1
source

Source: https://habr.com/ru/post/1271137/


All Articles