I'm working on a java spring mvc project. I have created CustomObjectMapper
class that extends ObjectMapper
form jackson. Also I set CustomObjectMapper
in the spring configuration, so every time jackson wants to serialize
or deserialize
, my CustomObjectMapper
works and everything is right. But I have one problem:
I have created a custom annotation @AllowHtml
and I have put it on top of some String
fields in my model. Also I have created a JsonDeserializerString
class in this way:
public class JsonDeserializerString extends JsonDeserializer<String>{
@Override
public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
return jp.getText();
}
}
And I set this deserializer in my CustomObjectMapper
in this way:
@Component
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper(){
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new JsonDeserializerString());
this.registerModule(module);
}
}
This works as expected and when a user submit a form, every string fields deserialize with JsonDeserializerString
. But I want to get field annotations in the deserializer. . In fact, I want to, If a string field has a certain annotation in the model, do some logics. How can I do this?
Your deserializer could implement ContextualDeserializer and extract the property annotations. You could store it in a private property and reuse it while deserializing the String.
Example:
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) { ... }
}
}
I hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.