Different JSON output when using custom json serializer in Spring Data Rest

后端 未结 4 1550
走了就别回头了
走了就别回头了 2020-12-09 05:43

After adding a custom Jackson serializer based on the official documenation I\'ve observed a slightly different json output format.

This example is base

4条回答
  •  無奈伤痛
    2020-12-09 06:07

    This is not a bug of Spring Data Rest it is actually the normal behaviour of the Jackson Serializer. Whenever you use the @JsonUnwrapped Annotation (as the Resource content field does) together with a custom Serializer the Jackson Serializer will explicitly write the field name (in this case content). Have a look at the UnwrappingBeanPropertyWriter for more details. Anyhow you have been on the right track using the UnwrappingBeanSerializer but the setup is slightly different then the usual Serializer registration. The following example should fix your problem:

    @Override
    protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
        mapper.registerModule(new Module() {
            @Override
            public String getModuleName() {
                return "my.module";
            }
    
            @Override
            public Version version() {
                return Version.unknownVersion();
            }
    
            @Override
            public void setupModule(SetupContext context) {
    
                context.addBeanSerializerModifier(new BeanSerializerModifier() {
                    @Override
                    public JsonSerializer modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer serializer) {
                        if(beanDesc.getBeanClass().equals(Order.class)) {
                            return new UnwrappingOrderSerializer((BeanSerializerBase) serializer, NameTransformer.NOP);
                        }
                        return serializer;
                    }
                });
            }
        });
    }
    
    public class UnwrappingOrderSerializer extends UnwrappingBeanSerializer {
        public UnwrappingBarSerializer(BeanSerializerBase src, NameTransformer transformer) {
            super(src, transformer);
        }
    
        @Override
        public JsonSerializer unwrappingSerializer(NameTransformer transformer) {
            return new UnwrappingOrderSerializer(this, transformer);
        }
    
        @Override
        protected void serializeFields(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
            Order order = (Order) bean;
            jgen.writeStringField("paid", order.isPaid();
        }
    
        @Override
        public boolean isUnwrappingSerializer() {
            return true;
        }
    }
    
        

    提交回复
    热议问题