Spring MVC忽略给定控制器方法的Json属性

Evg*_*rov 6 java spring json spring-mvc jackson

我有一个Java类(MyResponse)由多个RestController方法返回,并有很多字段.

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

@RequestMapping(value = "someOtherMethod", method=RequestMethod.POST)
public ResponseEntity<MyResponse> someOtherMethod(...) {}
Run Code Online (Sandbox Code Playgroud)

我想忽略(例如,不序列化)一个方法的属性之一.

我不想忽略该类的空字段,因为它可能对其他字段有副作用.

@JsonInclude(Include.NON_NULL)
public class MyResponse { ... }
Run Code Online (Sandbox Code Playgroud)

JsonView看起来不错,但据我了解我必须标注在类的所有其他领域有@JsonView不同之处,我想忽略这听起来笨拙的人.如果有办法做"反向JsonView"这样的话会很棒.

关于如何忽略控制器方法的属性的任何想法?

Evg*_*rov 5

支持这个家伙。

默认情况下(在 Spring Boot 中)MapperFeature.DEFAULT_VIEW_INCLUSION 在 Jackson 中启用。这意味着默认情况下包含所有字段。

但是,如果您使用与控制器方法上的视图不同的视图注释任何字段,则该字段将被忽略。

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;
}
Run Code Online (Sandbox Code Playgroud)