How to filter the json response returning from spring rest web service

前端 未结 4 1342
后悔当初
后悔当初 2021-01-17 03:28

How to filter the json response returning from spring rest web service.

When use call the customEvents i only need to outout the eventId and the Event name only. Whe

4条回答
  •  没有蜡笔的小新
    2021-01-17 04:14

    You can use @JsonView annotation for this purpose. But unfortunately it works only for 4.x and above.

    This is the cleanest way that I know:

    public class View {
        public interface Summary {}
        public interface Details extends Summary{}
    }
    
    Class CustomEvent{
        @JsonView(View.Summary.class)
        long id;
    
        @JsonView(View.Summary.class)
        String eventName;
    
        @JsonView(View.Details.class)
        Account createdBy;
    
        @JsonView(View.Details.class)
        Account modifiedBy;
    }
    
    @Controller
    public class CustomEventService
    {
        @JsonView(View.Summary.class)
        @RequestMapping("/customEvents")
        public @ResponseBody List getCustomEventSummaries() {}
    
        @RequestMapping("/customEvents/{eventId}")
        public @ResponseBody CustomEvent getCustomEvent(@PathVariable("eventId") Long eventId) {}
    }
    

    Keep in mind that by default fields that do not have the @JsonView annotation are also serialized. That's why you need to annotate them all.

    For more information please read: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

提交回复
热议问题