ham*_*med 4 java json spring-mvc jackson deserialization
我正在开发一个 java spring mvc 项目。我创建CustomObjectMapper了扩展ObjectMapper形式杰克逊的类。我也设置CustomObjectMapper了弹簧配置,所以每次杰克逊想要serialize或时deserialize,我的CustomObjectMapper作品和一切都是正确的。但我有一个问题:
我创建了一个自定义注释@AllowHtml,并将其放在String模型中的某些字段之上。我也JsonDeserializerString以这种方式创建了一个类:
public class JsonDeserializerString extends JsonDeserializer<String>{
@Override
public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
return jp.getText();
}
}
Run Code Online (Sandbox Code Playgroud)
我CustomObjectMapper以这种方式设置了这个解串器:
@Component
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper(){
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new JsonDeserializerString());
this.registerModule(module);
}
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作,当用户提交表单时,每个字符串字段都反序列化为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) { ... }
}
}
Run Code Online (Sandbox Code Playgroud)
我希望它有帮助。
| 归档时间: |
|
| 查看次数: |
2148 次 |
| 最近记录: |