15

We have good support for JSON in java http://blog.locut.us/main/2009/10/14/which-is-the-best-java-json-library.html but what about BSON.

What library do you know that provides BSON support for java? It should obviously be efficient in runtime.

0

5 Answers 5

7

You can use the MongoDB driver for Java to store a BSON object, then convert that to a String which you can then wrap with JSONObject.

For example, here's how I'll create a regular document:

BasicDBObject obj = new BasicDBObject();
obj.put("name", "Matt");
obj.put("date", new Date());

Then, to get a String representation of the object, simply call:

String bsonString = obj.toString();

Wrap it with a JSONObject and get the date attribute, which should return it in a BSON-compliant format.

JSONObject newObject = new JSONObject(bsonString);
System.out.println(newObject.get("date"));

The resulting output is something like:

{"$date":"2012-08-10T05:22:53.872Z"}
0
2

The BSON site is pointing at this

If you want to use it from MongoDB, take a look at this example

3
  • 3
    Guess I could take the encoding part from Mongo and make it an external library. Was hoping from something more "mature", thanks for the tip. Sep 7, 2010 at 8:08
  • 3
    to be honest the mongoDB example is a bit retarded! why it couldn't be as easy as json conversion? Jul 17, 2013 at 4:55
  • 7
    The answer has a broken link
    – seinecle
    Jan 14, 2017 at 11:32
1

In order to get our Model in MongoDB we used google gson to convert our model into JSON first and then we used the JSON util parse method from MongoDB to parse our generated JSON string to a DBObject which you can put in your MongoDB. I don't know about performance to be honest.

1
  • The problem with this approach is that you are going to lose some data types (such as Date).
    – Enrichman
    Sep 5, 2015 at 7:21
1

There is also a rather new BSON4Jackson project, which allows one to use Jackson for handling BSON data. This means full data binding (to/from POJOs), tree model, even streaming (incremental) reading/writing to degree it can be done with BSON format.

2
  • I hate Jackson. Its API just screams "overcomplication". Crockford's library is the best and the smallest. Jul 11, 2012 at 0:04
  • 4
    You are entitled to your ill-conceived opinion. Toy libs like org.json's reference implementation are probably a good fit for you.
    – StaxMan
    Jul 11, 2012 at 5:51
1

There is also ebson. I've not tried it...

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.