json Jackson反序列化错误处理

yc0p9oo0  于 2023-02-14  发布在  其他
关注(0)|答案(5)|浏览(165)

我的问题很简单:下面是一个简单的类:

public class Foo {
   private int id = -1;
   public void setId(int _id){ this.id = _id; }
   public int getId(){ return this.id; }
}

我正在尝试处理以下JSON:

{
  "id": "blah"
}

显然,这里有个问题(“blah”不能解析为int)
以前,Jackson会抛出类似于org.codehaus.jackson.map的异常:无法从字符串值“blah”构造java.lang.Integer的示例:不是有效的整数值
我同意这一点,但我想注册一些东西,允许忽略这种类型的Map错误。我尝试注册一个DeserializationProblemHandler(参见here),但它似乎只对未知属性起作用,而不是反序列化问题。
你对这个问题有什么头绪吗?

deyfvvtc

deyfvvtc1#

我成功地解决了我的问题,感谢来自JacksonML的塔图。
我不得不为Jackson中处理的每个原语类型使用自定义的非阻塞反序列化器。

public class JacksonNonBlockingObjectMapperFactory {

    /**
     * Deserializer that won't block if value parsing doesn't match with target type
     * @param <T> Handled type
     */
    private static class NonBlockingDeserializer<T> extends JsonDeserializer<T> {
        private StdDeserializer<T> delegate;

        public NonBlockingDeserializer(StdDeserializer<T> _delegate){
            this.delegate = _delegate;
        }

        @Override
        public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            try {
                return delegate.deserialize(jp, ctxt);
            }catch (JsonMappingException e){
                // If a JSON Mapping occurs, simply returning null instead of blocking things
                return null;
            }
        }
    }

    private List<StdDeserializer> jsonDeserializers = new ArrayList<StdDeserializer>();

    public ObjectMapper createObjectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();

        SimpleModule customJacksonModule = new SimpleModule("customJacksonModule", new Version(1, 0, 0, null));
        for(StdDeserializer jsonDeserializer : jsonDeserializers){
            // Wrapping given deserializers with NonBlockingDeserializer
            customJacksonModule.addDeserializer(jsonDeserializer.getValueClass(), new NonBlockingDeserializer(jsonDeserializer));
        }

        objectMapper.registerModule(customJacksonModule);
        return objectMapper;
    }

    public JacksonNonBlockingObjectMapperFactory setJsonDeserializers(List<StdDeserializer> _jsonDeserializers){
        this.jsonDeserializers = _jsonDeserializers;
        return this;
    }
}

然后像这样调用它(只将那些你想成为非阻塞的反序列化器作为反序列化器传递):

JacksonNonBlockingObjectMapperFactory factory = new JacksonNonBlockingObjectMapperFactory();
factory.setJsonDeserializers(Arrays.asList(new StdDeserializer[]{
    // StdDeserializer, here, comes from Jackson (org.codehaus.jackson.map.deser.StdDeserializer)
    new StdDeserializer.ShortDeserializer(Short.class, null),
    new StdDeserializer.IntegerDeserializer(Integer.class, null),
    new StdDeserializer.CharacterDeserializer(Character.class, null),
    new StdDeserializer.LongDeserializer(Long.class, null),
    new StdDeserializer.FloatDeserializer(Float.class, null),
    new StdDeserializer.DoubleDeserializer(Double.class, null),
    new StdDeserializer.NumberDeserializer(),
    new StdDeserializer.BigDecimalDeserializer(),
    new StdDeserializer.BigIntegerDeserializer(),
    new StdDeserializer.CalendarDeserializer()
}));
ObjectMapper om = factory.createObjectMapper();
pb3s4cty

pb3s4cty2#

您可能希望通过添加处理此特定异常的方法来让控制器处理此问题

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public String handleHttpMessageNotReadableException(HttpMessageNotReadableException ex)
{
    JsonMappingException jme = (JsonMappingException) ex.getCause();
    return jme.getPath().get(0).getFieldName() + " invalid";
}

当然,那条线

JsonMappingException jme = (JsonMappingException) ex.getCause();

在某些情况下可能会抛出类强制转换异常,但我还没有遇到过。

7cjasjjr

7cjasjjr3#

我写了一个简单的错误处理程序,它会给予你一些错误,你可以返回给用户的错误请求作为状态码。使用@JsonProperty required = true来获取与丢失属性相关的错误。Jackson版本2.9.8。

public class JacksonExceptionHandler {

    public String getErrorMessage(HttpMessageNotReadableException e) {
        String message = null;
        boolean handled = false;
        Throwable cause = e.getRootCause();

        if (cause instanceof UnrecognizedPropertyException) {
            UnrecognizedPropertyException exception = (UnrecognizedPropertyException) cause;
            message = handleUnrecognizedPropertyException(exception);
            handled = true;
        }
        if (cause instanceof InvalidFormatException) {
            InvalidFormatException exception = (InvalidFormatException) cause;
            message = handleInvalidFormatException(exception);
            handled = true;
        }
        if (cause instanceof MismatchedInputException) {
            if (!handled) {
                MismatchedInputException exception = (MismatchedInputException) cause;
                message = handleMisMatchInputException(exception);
            }
        }
        if (cause instanceof JsonParseException) {
            message = "Malformed json";
        }
        return message;
    }

    private String handleInvalidFormatException(InvalidFormatException exception) {
        String reference = null;
        if (!exception.getPath().isEmpty()) {
            String path = extractPropertyReference(exception.getPath());
            reference = removeLastCharacter(path);
        }
        Object value = exception.getValue();
        return "Invalid value '" + value + "' for property : " + reference;
    }

    private String handleUnrecognizedPropertyException(UnrecognizedPropertyException exception) {
        String reference = null;
        if (!exception.getPath().isEmpty()) {
            String path = extractPropertyReference(exception.getPath());
            reference = removeLastCharacter(path);
        }
        return "Unknown property : '" + reference + "'";
    }

    private String handleMisMatchInputException(MismatchedInputException exception) {
        String reference = null;
        if (!exception.getPath().isEmpty()) {
            reference = extractPropertyReference(exception.getPath());
        }
        String property = StringUtils.substringBetween(exception.getLocalizedMessage(), "'", "'");
        // if property missing inside nested object
        if (reference != null && property!=null) {
            return "Missing property : '" + reference + property + "'";
        }
        // if invalid value given to array
        if(property==null){
            return "Invalid values at : '"+ reference +"'";
        }
        // if property missing at root level
        else return "Missing property : '" + property + "'";
    }

    // extract nested object name for which property is missing
    private String extractPropertyReference(List<JsonMappingException.Reference> path) {
        StringBuilder stringBuilder = new StringBuilder();
        path.forEach(reference -> {
                    if(reference.getFieldName() != null) {
                        stringBuilder.append(reference.getFieldName()).append(".");
                        // if field is null means it is array
                    } else stringBuilder.append("[].");
                }
                );
        return stringBuilder.toString();
    }

    // remove '.' at the end of property path reference
    private String removeLastCharacter(String string) {
        return string.substring(0, string.length() - 1);
    }
}

在全局通知中调用这个类对象

@Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String message = new JacksonExceptionHandler().generator.getErrorMessage(ex);
        if(message == null){
            return ResponseEntity.badRequest().body("Malformed json");
        }
        return ResponseEntity.badRequest().body(message);
    }
z9ju0rcb

z9ju0rcb4#

创建一个简单的Map器:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JSONProcessingErroMapper implements ExceptionMapper<InvalidFormatException> {

@Override
public Response toResponse(InvalidFormatException ex) { 
    return Response.status(400)
             .entity(new ClientError("[User friendly message]"))
             .type(MediaType.APPLICATION_JSON)
             .build();
}

}

xoefb8l8

xoefb8l85#

DeserializationProblemHandler现在有了更多的方法,比如handleUnexpectedTokenhandleWeird*Value,它应该能够处理任何需要的东西。
子类化它,覆盖你需要的方法,然后用addHandler(DeserializationProblemHandler h)把它添加到你的ObjectMapper中。

相关问题