Thematrixme
Thematrixme

Reputation: 318

Bson - How to convert JSON to List<Document> and List<Document> to JSON?

I'm using Java Driver 3.0 with MongoDB in order to send JSONs through a webservice.

When I want to convert a Document object (org.bson.Document) to JSON, I use obj.toJson(), and when I want to convert a JSON to a Document object, I use Document.parse(json).

However when I'm dealing with lists of Documents (represented like this in JSON:[{"field1":1, ...}, {"field1":2, ...}]), I can't figure out a clean way of doing these conversions.

So far, I've come up with these "hacks":

I also tried to use another JSON serializer (I took Google's one), but it doesn't give the same result as the built-in toJson() method from the Document object, particularly for the "_id" field or the timestamps.

Is there any clean way of doing this?

Upvotes: 6

Views: 20710

Answers (2)

Sanchit Singhania
Sanchit Singhania

Reputation: 527

There is solution for driver 3.0.

You follow the following steps:

BasicDBObject dbObject = (BasicDBObject) JSON.parse("yourJsonString");
MongoCollection<BasicDBObject> table = db.getCollection("collectionName", BasicDBObject.class);
table.insertOne(dbObject);

Upvotes: 1

Blakes Seven
Blakes Seven

Reputation: 50406

The com.mongodb.util.JSON package is "still" not deprecated and does handle lists of DBObject quite well. You just need to do a little converting:

    MongoClient client = new MongoClient(new ServerAddress("192.168.2.4", 27017));

    MongoDatabase db = client.getDatabase("test");

    MongoCollection<Document> collection = db.getCollection("sample");

    MongoCursor<Document> iterator = collection.find().iterator();

    BasicDBList list = new BasicDBList();
    while (iterator.hasNext()) {
        Document doc = iterator.next();
        list.add(doc);
    }
    System.out.println(JSON.serialize(list));

And there is nothing wrong with adding that "list" to another DBObject wih the key "list" as used in your output. Otherwise you can delve into using another JSON parser and feeding each document from the cursor iterator into that.

It depends on the size of your input, but while this still works it sure looks a lot cleaner in code.

Upvotes: 9

Related Questions