【问题标题】:Can I ignore MismatchedInputException within ObjectMapper?我可以忽略 ObjectMapper 中的 MismatchedInputException 吗?
【发布时间】:2019-03-21 02:29:53
【问题描述】:

我正在使用 Jackson ObjectMapper 类,如下所示:

objectMapper.treeToValue(jsonNode, MyClass.class)

其中jsonNodeJsonNode 的一个实例。

当我拨打treeToValue() 时,我会收到带有消息的MismatchedInputException

Cannot deserialize instance of com.example.MyField` out of START_OBJECT token

因为MyField 被定义为MyClass 内部的字符串,但它是jsonNode 变量内部的JSON 对象。我完全可以接受jsonNode 的其中一个字段的类型不匹配,但我宁愿ObjectMapper 只是不尝试序列化该字段并忽略它而不是抛出MismatchedInputException

我试过了

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

但这只是忽略了缺失的字段,它不会做任何事情来阻止现有字段的MismatchedInputException

【问题讨论】:

  • 除非您不需要该字段,否则我认为您不能忽略它的功能;在这种情况下,您可以 catch MismatchedInputException 而什么都不做。但是,我不确定这就是您想要完成的。
  • @PerpetualJ 对,我仍然希望对所有其他字段进行序列化。好像如果我抓住MismatchedInputException 它只会跳过整个序列化过程
  • 看到这个问题和一些狡猾的答案:stackoverflow.com/questions/4783421/…
  • @user2121620 我相信如果你发现异常它会终止序列化过程。

标签: java json spring jackson objectmapper


【解决方案1】:

在 diginoise 提到的帖子中,你应该看看这个回复:

https://stackoverflow.com/a/40972234/9343066

【讨论】:

    【解决方案2】:

    您可以递归删除违规字段并重试。这是我想出的(可以根据您的日志记录和异常处理需求进行简化)。

    public class YourClass {
    
        private static final Logger LOGGER = Logger
                .getLogger(YourClass.class.getName());
    
        public final static ObjectMapper mapper = new ObjectMapper().configure(
                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
        public static <T> T toTypedObject(Class<T> type, JsonNode tree) {
            return toTypedObject(type, tree, true);
        }
    
        private static <T> T toTypedObject(Class<T> type, JsonNode tree,
                boolean topLevel) {
    
            T object;
    
            try {
                object = mapper.treeToValue(tree, type);
            } catch (MismatchedInputException e) {
                String originalTree = tree.toString();
                object = toTypedObject(type, tree, originalTree, e);
                if (topLevel) {
                    LOGGER.log(Level.WARNING, "Failed to convert node tree to a "
                            + type.getSimpleName()
                            + " object without modifications: " + originalTree, e);
                    LOGGER.log(Level.INFO,
                            "Modified node tree was successfully converted to a "
                                    + type.getSimpleName() + " object: " + tree);
                }
            } catch (JsonProcessingException e) {
                throw new YourException("Failed to convert node tree to a "
                        + type.getSimpleName() + " object: " + tree, e);
            }
    
            return object;
        }
    
        private static <T> T toTypedObject(Class<T> type, JsonNode tree,
                String originalTree,
                MismatchedInputException mismatchedInputException) {
    
            T object;
    
            List<Reference> path = mismatchedInputException.getPath();
            if (path != null && !path.isEmpty()) {
    
                try {
    
                    ObjectNode subNode = (ObjectNode) tree;
                    for (int i = 0; i < path.size(); i++) {
                        String fieldName = path.get(i).getFieldName();
                        if (i + 1 < path.size()) {
                            subNode = (ObjectNode) tree.get(fieldName);
                        } else {
                            subNode.remove(fieldName);
                        }
                    }
                    object = toTypedObject(type, tree, false);
    
                } catch (Exception e) {
                    throw new YourException("Failed to convert node tree to a "
                            + type.getSimpleName() + " object: " + originalTree,
                            mismatchedInputException);
                }
    
            } else {
                throw new YourException(
                        "Failed to convert node tree to a " + type.getSimpleName()
                                + " object: " + originalTree,
                        mismatchedInputException);
            }
    
            return object;
        }
    
    }
    

    致电:

    YourObject yourObject = YourClass.toTypedObject(YourObject.class, tree);
    

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2010-09-29
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2016-10-05
      相关资源
      最近更新 更多