How to return Java 'java.time.Instant' property as json value in Restful API body response?

user2868835 picture user2868835 · Jul 6, 2017 · Viewed 7.3k times · Source

I have a Spring Boot restful API service that returns a Java object in its response which is translated into json.

One of the Java object properties is a 'Java.time.Instant'. How should I translate this for the json object being returned?

update

I've tried using @JsonFormat but this doesn't work...

The Java object being returned has an 'Instant' property...

 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")
 public Instant getRequested() {
     return Requested;
}

This is coming back in the json response body as...

"requested": {
    "epochSecond": 1499342121,
    "nano": 868000000
},

I'm using Spring Boot 1.5.4

The controller method is...

@RequestMapping(value="/", method= RequestMethod.POST)
public AcceptedAccountRequest newRequest(@RequestBody NewAccountRequest aRequest) {
AcceptedAccountRequest anAcceptedRequest = createAccepted(aRequest);
return anAcceptedRequest;
}

Answer

user2868835 picture user2868835 · Jul 6, 2017

Solved it... I was mising theh jsr310 maven dependency

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

On clarification... if I want all Instant properties to be returned in json as UTC should i use the following format instruction, or is there another better way of doing this...

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")