Java jackson反序列化器-获取模型字段注释列表

Java jackson反序列化器-获取模型字段注释列表,java,json,spring-mvc,jackson,deserialization,Java,Json,Spring Mvc,Jackson,Deserialization,我正在从事一个JavaSpringMVC项目。我已经创建了CustomObjectMapper类,该类扩展了ObjectMapper表单。此外,我还在spring配置中设置了CustomObjectMapper,因此每次jackson想要序列化或反序列化,我的CustomObjectMapper都能正常工作。但我有一个问题: 我创建了一个自定义注释@allowtml,并将其放在模型中一些字符串字段的顶部。此外,我还以这种方式创建了一个JsonDeserializerString类: public

我正在从事一个JavaSpringMVC项目。我已经创建了
CustomObjectMapper
类,该类扩展了
ObjectMapper
表单。此外,我还在spring配置中设置了
CustomObjectMapper
,因此每次jackson想要
序列化
反序列化
,我的
CustomObjectMapper
都能正常工作。但我有一个问题:

我创建了一个自定义注释
@allowtml
,并将其放在模型中一些
字符串
字段的顶部。此外,我还以这种方式创建了一个
JsonDeserializerString
类:

public class JsonDeserializerString extends JsonDeserializer<String>{

    @Override
    public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {

        return jp.getText();
    }

}
@Component
public class CustomObjectMapper extends ObjectMapper {
     public CustomObjectMapper(){
         SimpleModule module = new SimpleModule();
         module.addDeserializer(String.class, new JsonDeserializerString());
         this.registerModule(module);
     }
}

这与预期的一样有效,当用户提交表单时,每个字符串字段都会使用
JsonDeserializerString
反序列化。但是我想在反序列化程序中获取字段注释。。事实上,我想,如果一个字符串字段在模型中有一个特定的注释,做一些逻辑。我如何才能做到这一点?

您的反序列化程序可以实现ContextualDeserializer并提取属性注释。您可以将其存储在私有属性中,并在反序列化字符串时重用它

示例:

public class EmbeddedDeserializer 
    extends JsonDeserializer<Object> 
    implements ContextualDeserializer {

    private Annotation[] annotations;

    @Override
    public JsonDeserializer<?> createContextual(final DeserializationContext ctxt, 
        final BeanProperty property) throws JsonMappingException {

        annotations = property.getType().getRawClass().getAnnotations();

        return this;
    }

    @Override
    public Object deserialize(final JsonParser jsonParser, 
        final DeserializationContext context) 
            throws IOException, JsonProcessingException {

            if (annotations contains Xxxx) { ... }
        }
}
公共类嵌入反序列化程序
扩展JsonDeserializer
实现ContextualDeserializer{
私有注释[]注释;
@凌驾
公共JsonDeserializer createContext(最终反序列化上下文ctxt,
最终BeanProperty属性)引发JsonMappingException{
annotations=property.getType().getRawClass().getAnnotations();
归还这个;
}
@凌驾
公共对象反序列化(最终JsonParser JsonParser,
最终反序列化(上下文)
抛出IOException、JsonProcessingException{
如果(注释包含Xxxx){…}
}
}
我希望有帮助