Creating BSON Object From JSON String


Answer :

... 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:




  • Document.parse(String)

  • Document.toJson()



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.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable