Spring Data Pagination returns no results with JSONView

后端 未结 6 1650
广开言路
广开言路 2021-02-06 02:53

I am using Spring data pagination in my REST Controller and returning Paged entity. I would like to control the data returned as JSON with the help of JSONViews.

I am a

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 03:52

    Still cleaner is to tell Jackson to Serialize all props for a bean of type Page. To do that, you just have to declare to adapt slighly the Jackson BeanSerializer : com.fasterxml.jackson.databind.ser.BeanSerializer Create a class that extends that BeanSerializer called PageSerialier and if the bean is of type Page<> DO NOT apply the property filtering.

    As show in the code below, i just removed the filtering for Page instances :

    public class MyPageSerializer extends BeanSerializer {
    
    /**
     * MODIFIED By Gauthier PEEL
     */
    @Override
    protected void serializeFields(Object bean, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonGenerationException {
        final BeanPropertyWriter[] props;
        // ADDED
        // ADDED
        // ADDED
        if (bean instanceof Page) {
            // for Page DO NOT filter anything so that @JsonView is passthrough at this level
            props = _props;
        } else {
            // ADDED
            // ADDED
            if (_filteredProps != null && provider.getActiveView() != null) {
                props = _filteredProps;
            } else {
                props = _props;
            }
        }
    
            // rest of the method unchanged
        }
    
        // inherited constructor removed for concision
    }
    

    Then you need to declare it to Jackson with a Module :

    public class MyPageModule extends SimpleModule {
    
        @Override
        public void setupModule(SetupContext context) {
    
            context.addBeanSerializerModifier(new BeanSerializerModifier() {
    
                @Override
                public JsonSerializer modifySerializer(SerializationConfig config, BeanDescription beanDesc,
                        JsonSerializer serializer) {
                    if (serializer instanceof BeanSerializerBase) {
                        return new MyPageSerializer ((BeanSerializerBase) serializer);
                    }
                    return serializer;
    
                }
            });
        }
    }
    

    Spring conf now : in your @Configuration create a new @Bean of the MyPageModule

    @Configuration
    public class WebConfigPage extends WebMvcConfigurerAdapter {
    
        /**
         * To enable Jackson @JsonView to work with Page
         */
        @Bean
        public MyPageModule myPageModule() {
            return new MyPageModule();
        }
    
    }
    

    And you are done.

提交回复
热议问题