Spring MVC Ignore Json property for a given controller method

Evgeni Dimitrov :

I have a Java class (MyResponse) that is returned by a multiple RestController methods and has a lot of 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 (e.g. not serialize it) one of the properties for just one method.

I don't want to ignore null fields for the class, because it may have a side effect on other fields.

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

The JsonView looks good, but as far as I understand I have to annotate all other fields in the class with a @JsonView except the one that I want to ignore which sounds clumsy. If there is a way to do something like "reverse JsonView" it will be great.

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

Evgeni Dimitrov :

Props to this guy.

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

But if you annotate any field with a view that is different than the one 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;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=469051&siteId=1