6

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?

1
  • 1
    you could use @JsonIgnore but that would be for all methods. Maybe subclass it and ignore? Commented Aug 23, 2017 at 8:06

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.