【问题标题】:jackson deserializer - get model field annotations listjackson deserializer - 获取模型字段注释列表
【发布时间】:2016-09-30 13:25:09
【问题描述】:

我正在开发一个 java spring mvc 项目。我创建了 CustomObjectMapper 类,该类扩展了 ObjectMapper 形式的 jackson。我还在弹簧配置中设置了CustomObjectMapper,所以每次杰克逊想要serializedeserialize,我的CustomObjectMapper 工作,一切正常。但是我有一个问题:

我创建了一个自定义注释@AllowHtml,并将它放在我模型中的一些String 字段之上。我也以这种方式创建了一个JsonDeserializerString 类:

public class JsonDeserializerString extends JsonDeserializer<String>{

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

        return jp.getText();
    }

}

我以这种方式在我的CustomObjectMapper 中设置了这个反序列化器:

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

这按预期工作,当用户提交表单时,每个字符串字段都会使用 JsonDeserializerString 反序列化。但我想在反序列化器中获取字段注释。。其实我想,如果一个字符串字段在模型中有一定的注解,做一些逻辑。我该怎么做?

【问题讨论】:

    标签: java json spring-mvc jackson deserialization


    【解决方案1】:

    您的反序列化器可以实现 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) { ... }
            }
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 2017-03-04
      • 2019-12-04
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多