Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating BSON object from JSON string

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?

like image 275
Maciek Sawicki Avatar asked Jun 25 '10 10:06

Maciek Sawicki


People also ask

How to convert string to BSON Document in Java?

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

Does MongoDB convert JSON to BSON?

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.

Is BSON more compact than 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.

How do I parse a BSON document?

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.


4 Answers

... 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()
like image 89
yair Avatar answered Sep 18 '22 12:09

yair


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/

like image 43
eskatos Avatar answered Sep 19 '22 12:09

eskatos


Use Document.parse(String json) from org.bson.Document. It returns Document object which is type of Bson.

like image 42
Lakindu Akash Avatar answered Sep 20 '22 12:09

Lakindu Akash


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.

like image 20
Hank Gay Avatar answered Sep 22 '22 12:09

Hank Gay