Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bson Document to Json in Java

This is my code:

MongoDBSingleton dbSingleton = MongoDBSingleton.getInstance();
MongoDatabase db;

try {
    db = dbSingleton.getTestdb();
    MongoIterable<String> mg = db.listCollectionNames();
    MongoCursor<String> iterator=mg.iterator();

    while (iterator.hasNext()) {
        MongoCollection<Document> table = db.getCollection(iterator.next());

        for (Document doc: table.find()) {  
            System.out.println(doc.toJson());
        }
    }

}

This the output of toJson:

"modified" : { "$date" : 1475789185087}

This is my output of toString:

{"modified":"Fri Oct 07 02:56:25 IST 2016"}

I want String date format in Json, how to do it?

like image 787
Bharath Karnam Avatar asked Oct 07 '16 18:10

Bharath Karnam


2 Answers

Sadly, IMO, MongoDB Java support is broken.

That said, there is a @deprecated class in the mongo-java-driver that you can use:

String json = com.mongodb.util.JSON.serialize(document);
System.out.println("JSON serialized Document: " + json);

I'm using this to produce fasterxml (jackson) compatible JSON from a Document object that I can deserialize via new ObjectMapper().readValue(json, MyObject.class).

However, I'm not sure what they expect you to use now that the JSON class is deprecated. But for the time being, it is still in the project (as of v3.4.2).

I'm importing the following in my pom:

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongodb-driver-async</artifactId>
  <version>3.4.2</version>
</dependency>
<!-- Sadly, we need the mongo-java-driver solely to serialize
     Document objects in a sane manner -->
<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.4.2</version>
</dependency>

I'm using the async driver for actually fetching and pushing updates to mongo, and the non-async driver solely for the use of the JSON.serialize method.

like image 148
Shadow Man Avatar answered Oct 08 '22 05:10

Shadow Man


No, it is not possible to produce the plain JSON. Please refer this link.

However, it can produce JSON in two modes.

1) Strict mode - Output that you have already got

2) Shell mode

Shell Mode:-

JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);           
System.out.println(doc.toJson(writerSettings));

Output:-

"createdOn" : ISODate("2016-07-16T16:26:51.951Z")

MongoDB Extended JSON

like image 27
notionquest Avatar answered Oct 08 '22 05:10

notionquest