我试图使用Jackson2ObjectMapperBuilderCustomizer将自定义问题处理程序添加到对象映射器:
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
ObjectMapper m = builder.build();
m.addHandler(
new DeserializationProblemHandler() {
@Override
public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
System.out.println("ahahahaa");
return super.handleUnknownProperty(ctxt, p, deserializer, beanOrClass, propertyName);
}
}
);
}
};
}
Run Code Online (Sandbox Code Playgroud)
但是当我自动装配ObjectMapper bean时,_problemHandlers属性为null。
我也尝试过使用以下命令自定义现有的ObjectMapper:
@Autowired
public customize(ObjectMapper mapper) {
...
}
Run Code Online (Sandbox Code Playgroud)
但是结果是一样的。我不知道谁可以删除此属性。我根本不会在另一个地方初始化对象映射器的其他构建器/工厂/等。我做错了什么?
我想为无法识别的字段和请求正文的其他错误设置自定义错误消息。我尝试了 ExceptionMapper 但它不起作用:/使用 quarkus 和 Jackson
public class ReqDTO {
private String a;
}
Run Code Online (Sandbox Code Playgroud)
发送请求时:
{
"a": "a"
}
Run Code Online (Sandbox Code Playgroud)
它看起来不错。但是发送时:
{
"a": "a",
"b": "b"
}
Run Code Online (Sandbox Code Playgroud)
有错误响应:
Unrecognized field "b"; (class ReqDTO), not marked as ignorable
Run Code Online (Sandbox Code Playgroud)
想要自定义此消息和其他错误的 json 正文(如太多字段)以拥有“BAD_JSON_SCHEMA”等消息。
尝试过
@Provider
public class ExHandler implements ExceptionMapper<JsonMappingException>{
public Respone toResponse(JsonMappingException e) {
//response bad field impl
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用。看起来像 json 处理异常更快。尝试使用“Exception”、“JsonParseException”但没有任何改变:/
@Path("/")
public class Controller {
@Post
@Consume(APPLICATION_JSON)
@Produces(TEXT_PLAIN)
public Response getA(@Valid ReqDTO reqDTO){
//logic
}
}
Run Code Online (Sandbox Code Playgroud)
@编辑
找到类似 DeserializationProblemHandler 的东西,但不知道如何更改 …