2

Assuming a java class

public class User(){
    String name;
    Date dateCreated;
}

and a Spring boot controller:

@RequestMapping(value = "getUser", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE))
public User getUser() {
   User newUser = new User();
   newUser.dateCreated = new Date();
   return newUser;
}

If I have a rest API endpoint that returns that User object in JSON format, as above, the dateCreated will be send in timestamp format instead of ISO. Is there any way to make Java return the date in Iso format other than having to specify a new return object that has Date as a String?

One way to do this would be to convert Date to a String and send that but I'm wondering if there's a more convenient way..

4
  • What content-type are you serializing to? Commented Jan 8, 2016 at 18:43
  • Ah, let me update my post, the response is returned in JSON format. Commented Jan 8, 2016 at 18:48
  • what library are you using for JSON serialization/de-serialization? Default for Spring Boot is Jackson. Commented Jan 8, 2016 at 18:51
  • ok im gonna level with you here, I have absolutely no clue, I never had to specify a library for JSON serialization/de-serialization this was always done automatically by spring boot so I want to assume that since the default is Jackson, then Jackson it is but I wouldn't be 100% for it. I just have the @RestController on top of my java class and everything is taken care of automatically. Commented Jan 8, 2016 at 18:55

1 Answer 1

10

Update your application.properties with the following:

spring.jackson.serialization.write-dates-as-timestamps:false

Now you can specify the format in your bean as follows:

public class User(){
    String name;
    @JsonFormat(pattern="yyyy-MM-dd")
    Date dateCreated;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am having issue here. The date displayed in the json format is 1 day less.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.