4

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

  • All key, value pairs are of type String
  • I want to serialize this document using Java, Looking at the api, I did not find anything, How can I serialize a DBObject as JSON on file?
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
daydreamer
  • 87,243
  • 191
  • 450
  • 722

3 Answers3

12

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

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
3

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).

Tyson
  • 1,685
  • 15
  • 36
2

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)));
Igor Bljahhin
  • 939
  • 13
  • 23
  • Very good! Put aside the creation of the example object, and you have a 2-liner that perfectly does the job with pretty printing. – Thomas Schütt Oct 14 '16 at 09:01