0

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 ?

Alexey
  • 362
  • 1
  • 5
  • 17
  • 2
    Either through custom mapping to a new object, or by creating your own serializer: https://stackoverflow.com/a/27952473/2082699 But if you only want the seconds, might be best to just create a new object you serialize instead of messing with the Duration. – Tom Cools Apr 16 '20 at 07:30
  • @TomCools Yes, it really work. Thanks a lot! – Alexey Apr 16 '20 at 07:49
  • could you upvote my answer in this case, so others can see this as well? – Tom Cools Apr 16 '20 at 07:57

2 Answers2

2

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.

Tom Cools
  • 1,098
  • 8
  • 23
2

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();
  }
}
Balázs Németh
  • 6,222
  • 9
  • 45
  • 60