【问题标题】:@JsonSerialize and @JsonDeserialize not working when included in an annotation@JsonSerialize 和 @JsonDeserialize 在包含在注释中时不起作用
【发布时间】:2019-11-13 04:15:33
【问题描述】:

我正在尝试创建一个自定义注释来标记一个给定的属性,当它被注释时,所以我有以下结构:

@JsonComponent
public class TokenSerializer {

    @JsonSerialize(using = IdToTokenSerializer.class) // This does not work 
    @JsonDeserialize(using = TokenToIdDeserializer.class) // This does not work 
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface TokenizedId {
        Class<?> value();
    }

    public static class IdToTokenSerializer extends JsonSerializer<Long> implements ContextualSerializer {
        ...
    }

    public static class TokenToIdDeserializer extends JsonDeserializer<Long> implements ContextualDeserializer {
        ...
    }
}

我为什么要这样使用?因为@TokenizedId 将提供一个类,有条件地会考虑在序列化器/反序列化器上做某事。该值是使用ContextualDeserializer 配置的,从@TokenizedId 获取类。

问题是,当我这样注释时,序列化器和反序列化器都不起作用:

@TokenizedId(MyClass.class)
private Long id;

但是当我这样使用时它们会起作用(从@TokenizedId 中删除@JsonSerialize@JsonDeserialize):

@JsonSerialize(using = IdToTokenSerializer.class)
@JsonDeserialize(using = TokenToIdDeserializer.class)
@TokenizedId(MyClass.class)
private Long id;

我个人不喜欢这种方法,因为开发人员在想要标记某些 id 时需要始终记住使用这三个注释,而且我希望 @TokenizedId 始终与这些序列化程序相关。

有没有办法让序列化器/反序列化器在另一个注释上注释时工作?

【问题讨论】:

    标签: java spring-boot jackson serialization


    【解决方案1】:

    我能够按照我想要的方式使注释工作,在查看 Jackson 库上的一些线索后,我找到了 @JacksonAnnotationsInside 注释:

    /**
     * Meta-annotation (annotations used on other annotations)
     * used for indicating that instead of using target annotation
     * (annotation annotated with this annotation),
     * Jackson should use meta-annotations it has.
     * This can be useful in creating "combo-annotations" by having
     * a container annotation, which needs to be annotated with this
     * annotation as well as all annotations it 'contains'.
     * 
     * @since 2.0
     */
    @Target({ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @JacksonAnnotation
    public @interface JacksonAnnotationsInside
    {
    
    }
    

    在我的注释中包含这个解决了这个问题:

    @JacksonAnnotationsInside
    @JsonSerialize(using = IdToTokenSerializer.class) 
    @JsonDeserialize(using = TokenToIdDeserializer.class)
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface TokenizedId {
        Class<?> value();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      相关资源
      最近更新 更多