![](/img/trans.png)
[英]How to define a generic list deserializer through annotations with Jackson?
[英]jackson deserializer - get model field annotations list
我正在研究一个java spring mvc项目。 我创建了CustomObjectMapper
类,扩展了ObjectMapper
表单jackson。 我CustomObjectMapper
spring配置中设置了CustomObjectMapper
,因此每次jackson想要serialize
或deserialize
serialize
,我的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
反序列JsonDeserializerString
。 但是我想在反序列化器中获得字段注释。 。 实际上,我想,如果一个字符串字段在模型中有一定的注释,那就做一些逻辑。 我怎样才能做到这一点?
您的反序列化程序可以实现ContextualDeserializer并提取属性注释。 您可以将其存储在私有属性中,并在反序列化String时重用它。
例:
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) { ... }
}
}
我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.