我是 Java 新手,所以如果这个问题没有达到所需的标准,我深表歉意:我正在从平面 mongodb 表加载数据,并希望将所有文档写入 Pojo,我将其称为 DataClass 。我的问题是,在某些情况下,字段的类型不正确。在下面的代码中,我使用 mapper.readValue
读取 Json 并将其转换为对象。如果其中一个字段错误,则整个循环失败。有没有办法按元素进行操作并忽略失败的情况或设置默认值?
List<DataClass> result = new ArrayList<>();
FindIterable<Document> documents = getCollection().find();
for (Document doc : documents) {
result.add(mapper.readValue(doc.toJson(), DataClass.class));
如有任何建议,我们将不胜感激。
最佳答案
我猜你正在寻找,
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
如果传递的 json 具有未知属性,序列化不会失败。
此外,根据文档,
JsonMappingException if the input JSON structure does not match structure expected for result type (or has other mismatch issues)
如果你朝那个方向看,你可以捕获JsonMappingException
。
关于java - 如果某些字段无法转换为对象,则 ObjectMapper 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62350374/