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

20,515

Solution 1

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

Solution 2

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

Solution 3

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)));
Share:
20,515
daydreamer
Author by

daydreamer

Hello Viewer, Some of the places to see my work are BonsaiiLabs My Website

Updated on September 25, 2020

Comments

  • daydreamer
    daydreamer over 3 years

    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?
  • user2081279
    user2081279 over 7 years
    Very good! Put aside the creation of the example object, and you have a 2-liner that perfectly does the job with pretty printing.