用户可理解的JsonMappingException

时间:2017-07-27 08:38:21

标签: java json error-handling jackson

我正在使用Jackson读取用户提供的JSON文件,将其映射到对象上。如果JSON结构中出现错误,我会得到一个用户无法读取的JsonMappingException。例如:

my.package.shadow.jackson.databind.JsonMappingException: Class java.util.ArrayList not subtype of [map type; class java.util.Map, [simple type, class java.lang.String] -> [collection type; class java.util.List, contains [simple type, class java.lang.String]]] (through reference chain: my.package.configuration.Configuration["conf"]->java.util.HashMap["foo"])
    at my.package.shadow.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:391)
    ...
Caused by: java.lang.IllegalArgumentException: Class java.util.ArrayList not subtype of [map type; class java.util.Map, [simple type, class java.lang.String] -> [collection type; class java.util.List, contains [simple type, class java.lang.String]]]
    at my.package.shadow.jackson.databind.type.TypeFactory.constructSpecializedType(TypeFactory.java:357)
    ...

有没有办法获得更易读的错误消息,或JSON源中与异常对应的行和列?

为了澄清,用户写了这个

{
    "conf": {
        "foo": ["bar"]
    }
}

但我希望

{
    "conf": {
        "foo": {
            "bar" : ["a", "b", "c"]
        }
    }
}

代码片段:

public class ReadConfiguration {
    public static Configuration readConfiguration(File file) {
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        Configuration conf = mapper.readValue(file, Configuration.class);
        return conf
    }
}

0 个答案:

没有答案