gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:26:23 26 4
gpt4 key购买 nike

我正在尝试创建一个自定义注释,以便在注释给定属性时始终对其进行标记,因此我具有以下结构:

@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 始终相关到这些序列化器。

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

最佳答案

我能够使注释按照我想要的方式工作,在 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();
}

关于java - @JsonSerialize 和 @JsonDeserialize 包含在注释中时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com