Mongo Java: how to serialize DBObject as JSON in a 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

  • 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 DBObject as JSON in a file?
+4
source share
3 answers

The BasicDBObject toString () method seems to return the serialization of the JSON object.

+12
source

It looks like the JSON class has a method of serializing objects in JSON (as well as for navigating in another way and parsing JSON to retrieve DBObject).

+3
source

I used a combination of BasicDBObject toString () and GSON library to obtain a printed copy of the 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))); 
+2
source

All Articles