Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 322
user2868835 Avatar asked Jul 06 '17 10:07

user2868835


2 Answers

  1. pom.xml add

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    
  2. application.properties add

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

link https://codeboje.de/jackson-java-8-datetime-handling/

like image 159
Steve Nash Avatar answered Nov 18 '22 08:11

Steve Nash


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")
like image 4
user2868835 Avatar answered Nov 18 '22 08:11

user2868835