我试图创建一个自定义批注,以始终在给定属性进行批注时将其标记化,因此我具有以下结构:
@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;
但是当我这样使用它们(从@JsonSerialize
移除@JsonDeserialize
和@TokenizedId
时,它们起作用了)
@JsonSerialize(using = IdToTokenSerializer.class)
@JsonDeserialize(using = TokenToIdDeserializer.class)
@TokenizedId(MyClass.class)
private Long id;
我个人不喜欢这种方法,因为当开发人员想要对某些id进行标记时,他们将始终需要记住使用这三个注释,而且我希望@TokenizedId
始终与这些序列化程序相关
在另一个注释上注释时,有没有办法使序列化器/反序列化器正常工作?
答案 0 :(得分: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();
}