karlitos
karlitos

Reputation: 1656

How to directly convert MongoDB Document do Jackson JsonNode in Java

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.

Upvotes: 1

Views: 3705

Answers (2)

Matthew
Matthew

Reputation: 11397

Appreciate this isn't what the OP asked for - but might be helpful to some. I've managed to do this in reverse using MongoJack. The key thing is to use the JacksonEncoder which can turn any Json-like object into a Bson object. Then use BsonDocumentWriter to write it to a BsonDocument instance.

    @Test
    public void writeBsonDocument() throws IOException {
        JsonNode jsonNode = new ObjectMapper().readTree("{\"wibble\": \"wobble\"}");

        BsonDocument document = new BsonDocument();
        BsonDocumentWriter writer = new BsonDocumentWriter(document);

        JacksonEncoder transcoder =
                new JacksonEncoder(JsonNode.class, null, new ObjectMapper(), UuidRepresentation.UNSPECIFIED);

        var context = EncoderContext.builder().isEncodingCollectibleDocument(true).build();

        transcoder.encode(writer,jsonNode,context);
        Assertions.assertThat(document.toJson()).isEqualTo("{\"wibble\": \"wobble\"}");
    }

Upvotes: 0

karlitos
karlitos

Reputation: 1656

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.

Upvotes: 2

Related Questions