I have Java app that takes data from external app. Incoming JSONs are in Strings. I would like to parse that Strings and create BSON objects.
Unfortunate I can\'t fi
Use Document.parse(String json) from org.bson.Document. It returns Document object which is type of Bson.
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/
... 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:
I am not sure about java but the mongoDB CPP driver has a function type
BSONObj fromjson(string)
which returns a BSONObj according to the string passed. There should be a same function in Java too.
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.
You'll find the answer to your question in the source code of https://github.com/mongodb/mongo/blob/master/src/mongo/db/jsobj.cpp Which has the BSON to JSON conversion.
Basically, stuff like
ObjectId("XXX") -> { "$oid" : "XXX" }/XXX/gi -> { "$regex" : "XXX", "$options" : "gi" }and so on...