1

I am using Mongo DB and on saveData method I'm trying to save the data object on Mongo DB. First I am converting the data object in JSON format and after I save the object on Mongo DB. But there's a problem. My Class Object has a atribute initialDate with Date Type, but when this code saves the object on Mongo the initialDate atribute is saved as a string, but I need that it be saved in date format. Someone can help me?

public void saveData(ClassObject data) {
    JSONObject jsonObject = new JSONObject(data);
    String dataJson = jsonObject.toString();
    DBObject dbObject = (DBObject) JSON.parse(dataJson);
    DBCollection table = mongoDB.getCollection(data
            .getModel().getProjectName());
    table.insert(dbObject);
}

Here the ClassObject

Class ClassObject {

private int value;
private ParentModel model;  
private Date initialDate;

...
//here get and setters
}
Erick
  • 147
  • 2
  • 12

2 Answers2

2

Converting the object to JSON will convert the date to a string as JSON does not have a date type.

You can manually set the initialDate in the dbObject like so

 dbObject.put("initialDate", data.getInitialDate());

and this should save the date as a date.

A better solution would be to use a library to map between the java classes and json, as described here https://stackoverflow.com/a/7684293/965322

Community
  • 1
  • 1
David Hodgson
  • 854
  • 8
  • 13
1

Your date is getting converted into string while doing toString on jsonObject. You need to convert it back to date type after you do JSON.parse -

DBObject dbObject = (DBObject) JSON.parse(dataJson);

// TODO: Convert dbObject's initialDate property back to date type here

DBCollection table = mongoDB.getCollection(data
        .getModel().getProjectName());
Mukesh Saini
  • 1,488
  • 1
  • 9
  • 16