Alexey
Alexey

Reputation: 377

How to change Duration Format in JSON Java

I have a class with some field

public class SomeClass {
   private Duration discussionTime;
}

When i try to send this class to frontend using @RestController in Spring, i see that answer:

"discussionTime": {
                "seconds": 7,
                "zero": false,
                "negative": false,
                "nano": 72000000,
                "units": [
                    "SECONDS",
                    "NANOS"
                ]
            }

Is there ways to set format of answer to "discussionTime": 7 ?

Upvotes: 0

Views: 5429

Answers (2)

Balázs Németh
Balázs Németh

Reputation: 6637

An option could be to use a MixIn.

Also JavaTimeModule could help you.

Depending on your use case you can create your own serializer as suggested by others or go for a more generic solution if you have to do this in multiple places.

Or maybe:

public class SomeClass {
  private Duration discussionTime;

  @JsonProperty("discussionTime")
  public long getDiscussionTimeSeconds() {
      return discussionTime.getSeconds();
  }
}

Upvotes: 2

Tom Cools
Tom Cools

Reputation: 1158

There are two ways you can do this:

But if you only want the seconds, might be best to just create a new object you serialize instead of messing with the Duration.

Upvotes: 2

Related Questions