Jackson: How to add custom property to the JSON without modifying the POJO

后端 未结 11 1275
南方客
南方客 2020-11-27 03:10

I am developing a REST interface for my app using Jackson to serialize my POJO domain objects to JSON representation. I want to customize the serialization for some types to

11条回答
  •  失恋的感觉
    2020-11-27 03:43

    You can do this (previous version did not work with Jackson after 2.6, but this works with Jackson 2.7.3):

    public static class CustomModule extends SimpleModule {
        public CustomModule() {
            addSerializer(CustomClass.class, new CustomClassSerializer());
        }
    
        private static class CustomClassSerializer extends JsonSerializer {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
                //Validate.isInstanceOf(CustomClass.class, value);
                jgen.writeStartObject();
                JavaType javaType = provider.constructType(CustomClass.class);
                BeanDescription beanDesc = provider.getConfig().introspect(javaType);
                JsonSerializer serializer = BeanSerializerFactory.instance.findBeanSerializer(provider,
                        javaType,
                        beanDesc);
                // this is basically your 'writeAllFields()'-method:
                serializer.unwrappingSerializer(null).serialize(value, jgen, provider);
                jgen.writeObjectField("my_extra_field", "some data");
                jgen.writeEndObject();
            }
        }
    }
    
    
    

    Update:

    I tried it out with Jackson 2.9.0 and 2.9.6 and it worked as expected with both. Perhaps try this out: http://jdoodle.com/a/z99 (run it locally - jdoodle apparently can't handle Jackson).

    提交回复
    热议问题