How to directly convert MongoDB Document do Jackson JsonNode in Java

Question

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());

In my understanding this will:

  1. Convert the Document to string
  2. Parse the string and create a JsonNode object

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.


Show source
| json   | jackson   | mongodb   | type-conversion   | bson   2017-10-02 17:10 1 Answers

Answers to How to directly convert MongoDB Document do Jackson JsonNode in Java ( 1 )

  1. 2017-10-05 09:10

    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);
    }
    

    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.

Leave a reply to - How to directly convert MongoDB Document do Jackson JsonNode in Java

◀ Go back