Search code examples
jsonmongodbspring-mvcdatetimespring-restcontroller

Issue with Spring mvc REST and mongoDB date field


I am having trouble with returning date stored in mongodb in the REST JSON response. I am using Spring-MVC 4.2.5 @RestController and @ResponseBody. I have date stored in Mongodb as "createdDate" : ISODate("2016-04-14T20:26:00.682Z"). when I return the collection back to the controller in spring mvc and return the JSON data back to the client, the entire DateTime (JODA) class is jsonified. I need only the date in DD-MM-YYYY format and not all other attributes. I do not want to store date as string in monngoDB.

This is how i am setting date:

  DateTime date = new DateTime(DateTimeZone.forID("Asia/Kolkata"));
    booking.setCreatedDate(date);

This is how it looks in MongoDB.

     "createdDate" : ISODate("2016-04-14T20:26:00.682Z")

This is how i am creating the response :

  Object resp;
  booking = getFromMongo(id);
  resp.setBooking(booking)
  return resp;

below is my JSON response

            "createdDate": {
            "year": 2016
            "minuteOfHour": 56
            "weekyear": 2016
            "yearOfEra": 2016
            "hourOfDay": 1
            "era": 1
            "dayOfMonth": 15
            "dayOfWeek": 5
            "dayOfYear": 106
            "secondOfMinute": 0
            "millisOfSecond": 764
            "weekOfWeekyear": 15
            "yearOfCentury": 16
            "monthOfYear": 4
            "centuryOfEra": 20
            "secondOfDay": 6960
            "minuteOfDay": 116
            "millisOfDay": 6960764
            "zone": {
            "uncachedZone": {
            "cachable": true
            "fixed": false
            "id": "Asia/Kolkata"
            }-
            "fixed": false
            "id": "Asia/Kolkata"
            }-
            "millis": 1460665560764
            "chronology": {
            "zone": {
            "uncachedZone": {
            "cachable": true
            "fixed": false
            "id": "Asia/Kolkata"
            }-
            "fixed": false
            "id": "Asia/Kolkata"
            }-
            }-
            "equalNow": false
            "beforeNow": true
            "afterNow": false
            }

How do i avoid jsonifying the entire DateTime class.


Solution

  • There are things that you need to do to format the date as yyyy-MM-dd:

    1.Add a dependency on com.fasterxml.jackson.datatype:jackson-datatype-joda.

    2.Configure Jackson not to format dates as timestamps by adding spring.jackson.serialization.write-dates-as-timestamps: false to your application.properties file.

    3.Annotate the LocalDataTime field or getter method with @JsonFormat(pattern="yyyy-MM-dd")

    That will be enough to have the json response as yyyy-MM-dd.you may face the time zone issue.