@JsonSerialize 和 @JsonDeserialize 包含在注释中时不起作用

nul*_*ptr 0 java serialization jackson spring-boot

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

@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 {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

@TokenizedId(MyClass.class)
private Long id;
Run Code Online (Sandbox Code Playgroud)

但是,他们在工作的时候使用这样(去除@JsonSerialize@JsonDeserialize@TokenizedId):

@JsonSerialize(using = IdToTokenSerializer.class)
@JsonDeserialize(using = TokenToIdDeserializer.class)
@TokenizedId(MyClass.class)
private Long id;
Run Code Online (Sandbox Code Playgroud)

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

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

nul*_*ptr 5

我能够使注释按照我想要的方式工作,在 Jackson lib 上寻找一些线索后,我找到了@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
{

}
Run Code Online (Sandbox Code Playgroud)

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

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