Creating BSON object from JSON string Creating BSON object from JSON string mongodb mongodb

Creating BSON object from JSON string


... And, since 3.0.0, you can:

import org.bson.Document;final Document doc = new Document("myKey", "myValue");final String jsonString = doc.toJson();final Document doc = Document.parse(jsonString);

Official docs:


Official MongoDB Java Driver comes with utility methods for parsing JSON to BSON and serializing BSON to JSON.

import com.mongodb.DBObject;import com.mongodb.util.JSON;DBObject dbObj = ... ;String json = JSON.serialize( dbObj );DBObject bson = ( DBObject ) JSON.parse( json );

The driver can be found here: https://mongodb.github.io/mongo-java-driver/


The easiest way seems to be to use a JSON library to parse the JSON strings into a Map and then use the putAll method to put those values into a BSONObject.

This answer shows how to use Jackson to parse a JSON string into a Map.