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

前端 未结 4 1315
后悔当初
后悔当初 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

    I can think of two solutions off hand which both take advantage of Jackson's mixin feature.

    The first solution which is by far more complicated but is an awesome approach if what you are describing will be replicated in other parts of the code is described in this link. What happens is that you define an aspect that applies the specific mixin (in your case CustomEventMixin) that you have set in the JsonFilter annotation.

    The second solution is far simpler and includes using the jackson object mapper on your own (instead of delegating this responsibility to String) like the following code

    @Controller
    public class EventController {
    
    
        private ObjectMapper objectMapper = new ObjectMapper();
    
        public EventController(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
            objectMapper.addMixInAnnotations(CustomEvent.class, CustomEventMixin.class);
        }
    
        @RequestMapping("/customEvents")
        @ResponseBody
        public String suggest()  {
            return objectMapper.writeValueAsString(getCustomEvents(), new TypeReference>() {});
        }
    }
    

    In both cases you need to define the CustomEventMixin according to Jackson rules

    UPDATE:

    An example Mixin class would be (say you want to ignore id)

    public interface CustomEventMixin {
    
        String name;
    
        @JsonIgnore
        String id;
    }
    

提交回复
热议问题