簡體   English   中英

Spring MVC忽略給定控制器方法的Json屬性

[英]Spring MVC Ignore Json property for a given controller method

我有一個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”這樣的話會很棒。

關於如何忽略控制器方法的屬性的任何想法?

道具給這個家伙。

默認情況下(在Spring Boot中)在Jackson中啟用了MapperFeature.DEFAULT_VIEW_INCLUSION。 這意味着默認情況下包含所有字段。

但是,如果您使用與控制器方法上的視圖不同的視圖注釋任何字段,則此字段將被忽略。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM