[英]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.