用
JsonParser.Feature.STRICT_DUPLICATE_DETECTION
ObjectMapper mapper = new ObjectMapper();mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);MyPOJO result = mapper.readValue(json, MyPOJO.class);
结果是:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Duplicate field 'email'
您也可以尝试使用
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY(更多信息)如果先将json字符串/输入反序列化为jackson
json树,然后反序列化为POJO,则会触发该问题。可以将其与自定义结合起来,
JsonDeserializer如下所示:
private static class MyPojoDeserializer extends JsonDeserializer<MyPOJO>{ @Override public MyPOJO deserialize(JsonParser p, DeserializationContext ctxt) throws IOException{ JsonNode tree = p.readValueAsTree(); return p.getCodec().treeToValue(tree, MyPOJO.class); }}
设置一次,并使用与以前相同的方式:
// setup ObjectMapper ObjectMapper mapper = new ObjectMapper();mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);SimpleModule module = new SimpleModule();module.addDeserializer(MyPOJO.class,new MyPojoDeserializer() );mapper.registerModule(module);// usemapper.readValue(json, MyPOJO.class);
结果:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Duplicate field 'email' for ObjectNode: not allowed when FAIL_ON_READING_DUP_TREE_KEY enabled
其他选择是自己在自定义反序列化器中或在POJO setter方法中实现所有逻辑。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)