【问题标题】:Default method in Jackson MixIn interface doesn't workJackson MixIn 接口中的默认方法不起作用
【发布时间】:2022-08-17 23:02:08
【问题描述】:

我正在使用我不控制源的 bean,例如:TheirClass

public class TheirClass {

    private String property;
}

我想为我使用MixIn 序列化的每个TheirClass 实例添加时间戳:

public interface TheirClassMixIn {

    @JsonProperty
    default long getTimestamp() {
        return System.currentTimeMillis();
    }

}

我让 Spring 知道:

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer someCustomizer() {
        return builder -> builder
                .mixIn(TheirClass.class, TheirClassMixIn.class);
    }

但这似乎不起作用。我错过了什么,如何实现为每个 TheirClass 实例添加一个固定的额外属性?

    标签: spring spring-boot jackson mixins


    【解决方案1】:

    你不能仅仅通过向混合类/接口添加属性来做到这一点,因为"Mix-in" annotations are a way to associate annotations with classes, without modifying (target) classes themselves, originally intended to help support 3rd party datatypes where user can not modify sources to add annotations.

    你可以通过在你的混入界面中添加@JsonAppend来使用它,这个注解是用于在对象被序列化时向对象添加常规属性之外的虚拟属性。

    它可以与混入功能一起使用,以避免修改原始 POJO。

    让我们重写你的例子:

    @JsonAppend(
        props = {
                @JsonAppend.Prop(
                        name = "timestamp", type = Long.class,
                        value = TimestampPropertyWriter.class
                )
        }
    )
    public interface TheirClassMixIn {}
    

    为了完成这个故事,我将展示TimestampPropertyWriter 的实现。它只是一个知道如何在给定TheirClass 实例的情况下评估我们的“虚拟”属性值的类:

    public class TimestampPropertyWriter extends VirtualBeanPropertyWriter {
    
        public TimestampPropertyWriter() {
        }
    
        public TimestampPropertyWriter(BeanPropertyDefinition propDef,
                                       Annotations contextAnnotations,
                                       JavaType declaredType) {
            super(propDef, contextAnnotations, declaredType);
        }
    
        @Override
        protected Object value(Object bean,
                               JsonGenerator gen,
                               SerializerProvider prov) {
            return System.currentTimeMillis();
        }
    
        @Override
        public VirtualBeanPropertyWriter withConfig(MapperConfig<?> config,
                                                    AnnotatedClass declaringClass,
                                                    BeanPropertyDefinition propDef,
                                                    JavaType type) {
            return new TimestampPropertyWriter(propDef, declaringClass.getAnnotations(), type);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多