GSON-序列化/反序列化延长日期的子类?

问题描述

我正在使用gson将对象序列化/反序列化为JSON(反之亦然)。我目前有一个扩展Date的SpecificDate类。问题是,当尝试反序列化SpecificDate时,它似乎不包含Date中的数据。这导致它在序列化时使用当前日期和时间。

代码中,我创建一个特定的日期,如下所示- SpecificDate date = new SpecificDate(1592337581L)然后将其序列化为JSON,然后反序列化回一个对象。而不是上面提供的很长的日期“ 2020-06-16T12:59:41.541”,它返回的是创建时间,因此,如果是今天创建,它将是这样的:2020-08 -11T12:51:44.542。

序列化SpecificDate时,JSON最终如下-

{
 "SpecificDate" : {  
   "fieldInSpecificDate" : "value"
 }
}

如何配置gson进行序列化和反序列化,以便能够正确序列化SpecificDate?


这是每个班级的样子

SpecificDate

    public class SpecificDate extends Date {
    int specificDateVal = 0;
    //Constructor
    public SpecificDate (long date){
        super(date);
    }
}

主类

public class Test {

    public static void main(String[] args){
        Gson gs = new Gson();

        SpecificDate date = new SpecificDate(1597210221L);

        System.out.println("This is the date : " + date);

        String tester = gs.toJson(date);

        System.out.println("This is the JSON after deserialization : \n" + tester);

        Date deserialized = gs.fromJson(tester,SpecificDate.class);

        System.out.println("This is date after serialization : " + deserialized);
    }
}

输出

This is the date : Mon Jan 19 03:40:10 PST 1970
This is the JSON after deserialization : 
{"specificDateVal":0}
This is date after serialization : Wed Dec 31 16:00:00 PST 1969

解决方法

我不确定您是否可以这样做。但是,您可以将数据简单地以Long形式存储在您的SpecificDate类中,该类表示时间。时间可以轻松转换为Date对象。

Date date = new Data(time); //where the time is your long

然后可以毫无问题地完成对象的序列化。 这只是我的建议,不过可能还有另一种方式。