9

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?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
Bharath Karnam
  • 103
  • 1
  • 1
  • 4

7 Answers7

10

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.

Shadow Man
  • 3,234
  • 1
  • 24
  • 35
3

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

notionquest
  • 37,595
  • 6
  • 111
  • 105
2

In theory we are supposed to use toJSON() per... https://jira.mongodb.org/browse/JAVA-1770

However, it seems that, at least up through 3.6, toJSON() isn't supported on various types the old JSON.serialize() method handled without issue, such as the AggregateIterable<Document> objects output by aggregate().

1

Here is a 2020 update to answer exactly your question, i.e. getting this exact format:

"modified":"2016-07-16T16:26:51.951Z"

You have to use writerSettings like notionquest suggested, but with a custom date converter and DateTimeFormatter.ISO_INSTANT:

public class JsonDateTimeConverter implements Converter<Long> {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class);
    static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT
        .withZone(ZoneId.of("UTC"));

    @Override
    public void convert(Long value, StrictJsonWriter writer) {
        try {
            Instant instant = new Date(value).toInstant();
            String s = DATE_TIME_FORMATTER.format(instant);
            writer.writeString(s);
        } catch (Exception e) {
            LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e);
        }
    }
}

Use it like this:

doc.toJson(JsonWriterSettings
            .builder()
            .dateTimeConverter(new JsonDateTimeConverter())
            .build())
Benjamin Caure
  • 2,090
  • 20
  • 27
1

if the bson.jar version is > 3.0.0 you may try document.toJson()

chendu
  • 684
  • 9
  • 21
0

I used following

try {

            MongoDatabase db = mongoClient.getDatabase("dbname");

            MongoCollection<Document> collection = db.getCollection("nameofcollect");

            Gson gson = new Gson();

            ArrayList<JsonObject> array = new ArrayList<JsonObject>();


            String jsonString = null;
            /*WARNING Gson lib serialize string ->means add slash if you convert "json string" into "json string"*/
            for (Document doc : collection.find()) {
                 jsonString = gson.toJson(doc);              
                 array.add(new Gson().fromJson(jsonString, JsonObject.class));
            }

            //String finalarry = gson.toJson(array);

            Map<Object, ArrayList<JsonObject>> seedMap = new HashMap<Object, ArrayList<JsonObject>>();
            // String encode = coCoRy.encryptAndEncode(jsonString);
            seedMap.put("seed", array);     
            String seedJsonString = gson.toJson(seedMap);

            mongoClient.close();

            return seedJsonString;


        } catch (MongoException | ClassCastException e) {
            e.printStackTrace();
            return null;
        }

Result will be like following

{
    "seed": [
        {
            "_id": {
                "timestamp": 1590914828,
                "counter": 10457170,
                "randomValue1": 5587428,
                "randomValue2": -25784
            },
            "FIR_EVID_NUM": "3436345346",
            "FIR_REG_NUM": "89678967",
            "LOGIN_ID": "pc_admin",
            "MEDIA_PATH": "C:\\Users\\ALPHAMALE\\Documents\\ShareX\\Screenshots\\2020-05\\1590211570.png"
        },
        {
            "_id": {
                "timestamp": 1590924463,
                "counter": 7254997,
                "randomValue1": 5012578,
                "randomValue2": 24700
            },
            "FIR_EVID_NUM": "999999",
            "FIR_REG_NUM": "888888",
            "LOGIN_ID": "32323",
            "MEDIA_PATH": "C:/uploads/c46847c7e2d130ffd746c789c0f0932e.png"
        }
    ]
}
Vinod Joshi
  • 7,696
  • 1
  • 50
  • 51
0

try this:

final JsonWriterSettings settings = JsonWriterSettings.builder( ).outputMode( JsonMode.SHELL ).build( );

System.out.println(doc.toJson(settings));

You can change the JsonMode is you wish

eheck
  • 325
  • 2
  • 7