0

I have a abstract class below and annotated @SerializedName on methods, and expected that Gson should generate "findOffsetDuration" in final result, but it didn't. Anyway to generate that computed property?

    public abstract static class BaseSyncTimedReport extends TimedReport {
        protected Date findOffsetEndTime = new Date();
        protected Date findNextBatchEndTime = new Date();
        protected Date batchSyncEndTime = new Date();

        @SerializedName("findOffsetDuration")
        public long findOffsetDuration() {
            return Duration.between(startTime.toInstant(), findOffsetEndTime.toInstant()).toMillis();
        }

        @SerializedName("findNextBatchDuration")
        public long findNextBatchDuration() {
            return Duration.between(findOffsetEndTime.toInstant(), findNextBatchEndTime.toInstant()).toMillis();
        }

        @SerializedName("batchSyncDuration")
        public long batchSyncDuration() {
            return Duration.between(findNextBatchEndTime.toInstant(), batchSyncEndTime.toInstant()).toMillis();
        }
Acech
  • 1
  • Does this answer your question? [Why does GSON use fields and not getters/setters?](https://stackoverflow.com/questions/6203487/why-does-gson-use-fields-and-not-getters-setters) – Marcono1234 Sep 23 '22 at 13:47
  • You could however write your own [`TypeAdapterFactory`](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/TypeAdapterFactory.html) which gets the methods of the class and creates an adapter which calls them for serialization. There might also be extensions developed by the community to support this, e.g. [gson-fire](https://github.com/julman99/gson-fire) (not sure if that is still actively maintained). – Marcono1234 Sep 23 '22 at 13:51

0 Answers0