抛出验证异常 - 使用行号

时间:2015-05-13 10:58:03

标签: java json jackson

我正在将JSON字符串映射到POJO而没有任何问题。 POJO构造函数放置了一些验证约束(整数属性必须为正,等等),并抛出IllegalArgumentException。

我尽力用违规数据(或其上下文,比如父JSON对象)的行号来表示,与呈现JSON语法错误的方式非常相似。

我的调查显示这不是微不足道的,但有可能吗?

微米。

1 个答案:

答案 0 :(得分:1)

是的,有可能。您可以在反序列化程序中访问解析器位置信息。您应该注册一个deserializer modifier,它将包装标准的desiralizer并捕获创建异常。在异常处理程序中,您可以将位置信息添加到异常对象中。

这是一个完整的例子:

public class JacksonLocationInException {
    public static class Bean {
        public final String field;

        @JsonCreator
        public Bean(@JsonProperty("field") final String field) {
            if ("invalid".equals(field)) {
                throw new IllegalArgumentException("Field is invalid");
            }
            this.field = field;
        }
    }

    private static class DelegatingJsonDeserializer extends DelegatingDeserializer {

        public DelegatingJsonDeserializer(final JsonDeserializer<?> delegatee) {
            super(delegatee);
        }

        @Override
        protected JsonDeserializer<?> newDelegatingInstance(
                final JsonDeserializer<?> newDelegatee) {
            return this._delegatee;
        }

        @Override
        public Object deserialize(final JsonParser jp, final DeserializationContext ctxt)
                throws IOException {
            try {
                return super.deserialize(jp, ctxt);
            } catch (final JsonMappingException e) {
                throw new JsonMappingException(e.getMessage(), jp.getCurrentLocation(), e);
            }
        }
    }

    private static class MyBeanDeserializerModifier extends BeanDeserializerModifier {
        @Override
        public JsonDeserializer<?> modifyDeserializer(
                final DeserializationConfig config,
                final BeanDescription beanDesc,
                final JsonDeserializer<?> deserializer) {
            return new DelegatingJsonDeserializer(deserializer);
        }
    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new MyBeanDeserializerModifier());
        mapper.registerModule(module);
        final String json = "{          " +
                "\"field\":\"invalid\"}";
        System.out.println(mapper.readValue(json, Bean.class));
    }

}

以下是包含行号和列号的输出:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class stackoverflow.JacksonLocationInException$Bean] value failed: Field is invalid (through reference chain: stackoverflow.Bean["field"])
 at [Source: {          "field":"invalid"}; line: 1, column: 30]
    at stackoverflow.JacksonLocationInException$DelegatingJsonDeserializer.deserialize(JacksonLocationInException.java:52)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3562)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2578)
    at stackoverflow.JacksonLocationInException.main(JacksonLocationInException.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class stackoverflow.JacksonLocationInException$Bean] value failed: Field is invalid (through reference chain: stackoverflow.Bean["field"])
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.wrapException(StdValueInstantiator.java:396)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromObjectWith(StdValueInstantiator.java:231)
    at com.fasterxml.jackson.databind.deser.impl.PropertyBasedCreator.build(PropertyBasedCreator.java:167)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:386)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1073)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:142)
    at com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer.deserialize(DelegatingDeserializer.java:108)
    at stackoverflow.JacksonLocationInException$DelegatingJsonDeserializer.deserialize(JacksonLocationInException.java:50)
    ... 8 more
Caused by: java.lang.IllegalArgumentException: Field is invalid
    at stackoverflow.JacksonLocationInException$Bean.<init>(JacksonLocationInException.java:28)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at com.fasterxml.jackson.databind.introspect.AnnotatedConstructor.call(AnnotatedConstructor.java:125)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromObjectWith(StdValueInstantiator.java:227)
    ... 15 more