我想为一个自定义注解提供一个特定的编写器和读取器。我确实有一些类需要字段的特定格式。理想的解决方案是创建一个自定义注解,并提供自己的类来读写用它注解的字段。
class SampleWithSpecificFormat { @MyAnnotation private String special; // Written and read via a custom class }
你有任何资源来解释如何做到这一点吗?
i7uq4tfw1#
我目前正在开发一个类似的功能。下面是一个例子。我已经重新命名并缩短了课程。我希望我已经了解了你在寻找什么,它可以帮助你。
MyDto
public class MyDto { @MyAnnotation(value = "FooBar") @JsonSerialize(using = SpecialSerializer.class) @JsonDeserialize(using = SpecialDeserializer.class) private String special; }
MyAnnotation
// Annotation @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented public @interface MyAnnotation { String value() default ""; }
SpecialSerializer
public class SpecialSerializer extends JsonSerializer<String> implements ContextualSerializer { private final String annotationValue; public SalutationSerializer() { this(null); } public SalutationSerializer(String annotationValue) { this.annotationValue = annotationValue; } @Override public void serialize(String popertyValue, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { // this.annotationValue --> "FooBar" jsonGenerator.writeString(popertyValue + "_manipulated"); } @Override public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) { return new SpecialSerializer( new MyAnnotationReader().getValue(property) ); } }
SpecialDeserializer
// SpecialDeserializer public class SpecialDeserializer extends JsonDeserializer<String> implements ContextualDeserializer { private final String annotationValue; public SpecialDeserializer() { this(null, null); } public SpecialDeserializer(String annotationValue) { this.annotationValue = annotationValue; } @Override public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { String popertyValue = jsonParser.getText(); // this.annotationValue --> "FooBar" return popertyValue + "_manipulated"; } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) { return new SpecialDeserializer( new MyAnnotationReader().getValue(property) ); } }
MyAnnotationReader
public class MyAnnotationReader { public String getMap(BeanProperty property) { MyAnnotation annotation = property.getAnnotation(MyAnnotation.class); return annotation.value(); } }
1条答案
按热度按时间i7uq4tfw1#
我目前正在开发一个类似的功能。下面是一个例子。我已经重新命名并缩短了课程。我希望我已经了解了你在寻找什么,它可以帮助你。
MyDto
MyAnnotation
SpecialSerializer
SpecialDeserializer
MyAnnotationReader