daydreamer
daydreamer

Reputation: 91959

Mongo Java: How to serialize DBObject as JSON on file?

I have a document in MongoDB as

name: name
date_created: date
p_vars: {
   01: {
      a: a,
      b: b,
   }
   02: {
      a: a,
      b: b,
   }
   ....
}

represented as DBObject

Upvotes: 4

Views: 21088

Answers (3)

Igor Bljahhin
Igor Bljahhin

Reputation: 987

I used the combination of BasicDBObject's toString() and GSON library in the order to get pretty-printed JSON:

    com.mongodb.DBObject obj = new com.mongodb.BasicDBObject();
    obj.put("_id", ObjectId.get());
    obj.put("name", "name");
    obj.put("code", "code");
    obj.put("createdAt", new Date());

    com.google.gson.Gson gson = new com.google.gson.GsonBuilder().setPrettyPrinting().create();

    System.out.println(gson.toJson(gson.fromJson(obj.toString(), Map.class)));

Upvotes: 2

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

It seems that BasicDBObject's toString() method returns the JSON serialization of the object.

Upvotes: 12

Tyson
Tyson

Reputation: 1715

Looks like the JSON class has a method to serialize objects into JSON (as well as to go the other way and parse JSON to retrieve a DBObject).

Upvotes: 3

Related Questions