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 find API for that in Java's BSON implementation.
Do I have use external parser for that like GSON?
bson. Document; final Document doc = new Document("myKey", "myValue"); final String jsonString = doc. toJson(); final Document doc = Document. parse(jsonString);
Does MongoDB use BSON, or JSON? MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.
It is not a mandate that the BSON files are always smaller than JSON files, but it surely skips the records which are irrelevant, while in the case of JSON, you need to parse each byte. This is the main reason for using it inside MongoDB. The BSON type format is lightweight, highly traversable and fast in nature.
BSON documents are lazily parsed as necessary. To begin parsing a BSON document, use one of the provided Libbson functions to create a new bson_t from existing data such as bson_new_from_data(). This will make a copy of the data so that additional mutations may occur to the BSON document.
... 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/
Use Document.parse(String json)
from org.bson.Document
. It returns Document
object which is type of Bson
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With