我已经编写了自定义JSON反序列化器,并且按预期方式工作,但是我的问题是它始终处于ON状态,因为它是在配置级别定义的。
我想在方法或控制器级别的某些自定义注释上禁用它,因此当存在该注释时它不起作用,但是当没有注释时,自定义JSON反序列化器将起作用。那可能吗 ?
我的反序列化代码:
@Configuration
public class OwaspConfiguration extends WebMvcConfigurerAdapter{
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jsonConverter());
}
@Bean
public HttpMessageConverter<?> jsonConverter() {
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new DefaultJsonSerializer());
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
objectMapper.registerModule(module);
return new MappingJackson2HttpMessageConverter(objectMapper);
}
}
public class DefaultJsonSerializer extends JsonDeserializer<String> implements ContextualDeserializer {
public static final org.owasp.html.PolicyFactory POLICY_FACTORY = new HtmlPolicyBuilder().toFactory();
@Override
public String deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
String value = parser.getValueAsString();
if (StringUtils.isEmpty(value))
return value;
else {
String originalWithUnescaped = unescapeUntilNoHtmlEntityFound(value);
return unescapeEntities(POLICY_FACTORY.sanitize(originalWithUnescaped), true);
}
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException {
return this;
}
private String unescapeUntilNoHtmlEntityFound(final String value) {
String unescaped = unescapeEntities(value, true);
if (!unescaped.equals(value))
return unescapeUntilNoHtmlEntityFound(unescaped);
else
return unescaped;
}
}
答案 0 :(得分:0)
使用@JsonDeserialize-用于附加到“设置”方法或字段或值类的注解,用于配置反序列化方面
在您的DTO中
@JsonDeserialize(using = StringDeserializer.class)
public String heading;
反序列化器类
public class StringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return p.getValueAsString();
}
}