本文介绍了如何编写处理字段的自定义注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究注解,希望有人指出我正确的方向.
i am delving into annotations and would like someone to point me in the right direction.
我想创建一个注释,当将其从JSON映射到POJO时,它能够修剪String值.
I want to create an annotation that will be able to trim the String value when it is being mapped from a JSON into a POJO.
不确定如何做到.
即
@trim
private String referenceField;
推荐答案
@JacksonAnnotationsInside
@Retention(RUNTIME)
@Target(FIELD)
@JsonDeserialize(using = StringStripDeserializer.class)
public @interface @Strip {}
class StringStripDeserializer extends StdDeserializer<String> {
@Override
public Date deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
String text = parser.getText();
return text != null ? text.strip : null;
}
...
}
或者,如果要修剪所有所有字符串:
Or, if you want to trim all the strings:
@Bean
public Module stringStripModule() {
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, (JsonParser jsonParser, DeserializationContext deserializationContext) => {
String string = super.deserialize(jsonParser, deserializationContext);
return Objects.nonNull(string) ? string.strip() : null;
});
return module;
}
这篇关于如何编写处理字段的自定义注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!