com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段“type” - 我如何得到no。抛出此异常的次数

时间:2018-05-14 01:32:16

标签: java json jackson

我从URL获取JSON响应,并且它具有属性名称misspelt。在这种情况下,将使用propertyName抛出UnrecognizedPropertyException。如何跟踪属性名称以及属性拼写错误的次数。下面是一段代码:

ObjectMapper objectMapper = new ObjectMapper();
int counter = 0;
JsonContainer[] jc = null;
URL url = new URL("sample_url");
try {
  jc = objectMapper.readValue(url, JsonContainer[].class);
}
catch(UnrecognizedPropertyException e) {
    counter++;
    e.getPropertyName();    
}

此处计数器始终返回1,但属性名称拼写错误不止一次。另外,我如何从抛出的异常中获取属性名称

1 个答案:

答案 0 :(得分:0)

如果您想跳过未知属性,但是要收集缺失属性的名称和计数,您可以提供自己的DefaultDeserializationContext实现,覆盖reportUnknownProperty(...)方法,例如

public final class ReportingDeserializationContext extends DefaultDeserializationContext {
    private static final long serialVersionUID = 1L;

    public ReportingDeserializationContext() {
        super(BeanDeserializerFactory.instance, null);
    }
    private ReportingDeserializationContext(ReportingDeserializationContext src, DeserializationConfig config, JsonParser jp, InjectableValues values) {
        super(src, config, jp, values);
    }
    private ReportingDeserializationContext(ReportingDeserializationContext src, DeserializerFactory factory) {
        super(src, factory);
    }
    @Override
    public DefaultDeserializationContext createInstance(DeserializationConfig config, JsonParser jp, InjectableValues values) {
        return new ReportingDeserializationContext(this, config, jp, values);
    }
    @Override
    public DefaultDeserializationContext with(DeserializerFactory factory) {
        return new ReportingDeserializationContext(this, factory);
    }

    @Override
    public void reportUnknownProperty(Object instanceOrClass, String fieldName, JsonDeserializer<?> deser) throws JsonMappingException {
        Class<?> clazz = (instanceOrClass instanceof Class ? (Class<?>) instanceOrClass : instanceOrClass.getClass());
        System.out.println("Unknown Property: " + clazz.getName() + "." + fieldName);
    }
}

测试

public class Test {
    public int a;

    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper(null, null, new ReportingDeserializationContext());
        Test jc = objectMapper.readValue("{ \"a\": 10, \"b\": 11, \"c\": 12 }", Test.class);
        System.out.println(jc.a);
    }
}

输出

Unknown Property: Test.b
Unknown Property: Test.c
10

我会留给你记录和计算未知属性,而不是像上面那样打印它们。