【问题标题】:Spring MVC Ignore Json property for a given controller methodSpring MVC忽略给定控制器方法的Json属性
【发布时间】:2018-01-31 16:55:57
【问题描述】:

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

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

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

我想忽略(例如不序列化它)仅一种方法的属性之一。

我不想忽略该类的空字段,因为它可能会对其他字段产生副作用。

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

JsonView 看起来不错,但据我了解,我必须用 @JsonView 注释类中的所有其他字段,除了我想忽略的那个听起来很笨拙的字段。如果有办法做类似“反向 JsonView”的事情,那就太好了。

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

【问题讨论】:

  • 您可以使用@JsonIgnore,但这适用于所有方法。也许将其子类化并忽略?

标签: java json spring spring-mvc jackson


【解决方案1】:

this guy 的道具。

默认情况下(在 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;
}

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 2021-08-26
    • 2018-03-31
    • 2016-06-26
    • 2011-05-22
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多