本文介绍了如何在Java中直接转换MongoDB Document做Jackson JsonNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将MongoDB文档(org.bson.Document)存储为Jackson JsonNode文件类型.在此启发下,此处有一个过时的答案.能够成功解析

I would like to store a MongoDB Document (org.bson.Document) as a Jackson JsonNode file type. There is a outdated answer to this problem here, inspired by this I was able to succesfully parse the Document with

ObjectMapper mapper = new ObjectMapper();
...
JonNode jsonData = mapper.readTree(someBsonDocument.toJson());

据我了解,这将是

  1. 将文档转换为字符串
  2. 解析字符串并创建一个JsonNode对象

我注意到 Jackson Project - jackson-datatype-mongo 杰克逊的BSON ,但我不知道如何使用它们更有效地进行转换.

I noticed there is some support for MongoDB/BSON for the Jackson Project - jackson-datatype-mongo and BSON for Jackson, but I can not figure out how to use them to do the conversion more efficiently.

推荐答案

我能够使用bson4jackson找出一些解决方案:

I was able to figure-out some solution using bson4jackson:

public static InputStream documentToInputStream(final Document document) {
    BasicOutputBuffer outputBuffer = new BasicOutputBuffer();
    BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer);
    new DocumentCodec().encode(writer, document, EncoderContext.builder().isEncodingCollectibleDocument(true).build());
    return new ByteArrayInputStream(outputBuffer.toByteArray());
}

public static JsonNode documentToJsonNode(final Document document) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new BsonFactory());
    InputStream is = documentToInputStream(document);
    return mapper.readTree(is);
}

我不确定这是否是最有效的方法,我认为这是比将BSOn转换为String并解析该字符串更好的解决方案. mongoDB JIRA中有一个公开票证,用于添加来自 Document的转换, DBObject BsonDocument 转换为 toBson ,反之亦然,这将大大简化整个过程.

I am not sure if this is the most efficient way, I am assuming it is still better solution than converting BSOn to String and parsing that string. There is an open Ticket in the mongoDB JIRA for adding conversion from Document, DBObject and BsonDocument to toBson and vice versa, which would simplify the whole process a lot.

这篇关于如何在Java中直接转换MongoDB Document做Jackson JsonNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:20