问题
I am trying to create a custom annotation to tokenize a given property always when it is annotated with, so I have the following structure:
@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 {
...
}
}
Why am I using like that? Because the @TokenizedId
will provide a class, which conditionally will be considered on the serializer/deserializer to do something. This value is configured using the ContextualDeserializer
, fetching the class from @TokenizedId
.
The issue is, both serializer and deserializer do not work when I annotate just like this:
@TokenizedId(MyClass.class)
private Long id;
But they work when I use like this (removing the @JsonSerialize
and @JsonDeserialize
from @TokenizedId
):
@JsonSerialize(using = IdToTokenSerializer.class)
@JsonDeserialize(using = TokenToIdDeserializer.class)
@TokenizedId(MyClass.class)
private Long id;
Personally I did not like this approach, since developers will need to always remember to use these three annotations when they would like to tokenize some id, and also I would like the @TokenizedId
always be related to these serializers.
Is there a way to make the serializer/deserializer work when annotated on another annotation?
回答1:
I was able to make the annotation works the way I wanted, looking after some clue on the Jackson lib, I found the @JacksonAnnotationsInside
annotation:
/**
* 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
{
}
Including this on my annotation solved the issue:
@JacksonAnnotationsInside
@JsonSerialize(using = IdToTokenSerializer.class)
@JsonDeserialize(using = TokenToIdDeserializer.class)
@Retention(RetentionPolicy.RUNTIME)
public static @interface TokenizedId {
Class<?> value();
}
来源:https://stackoverflow.com/questions/56853750/jsonserialize-and-jsondeserialize-not-working-when-included-in-an-annotation