How to serialize Date to long using gson?

后端 未结 2 1995
情歌与酒
情歌与酒 2021-02-19 05:26

I recently switched some of our serialization from Jackson to Gson. Found out that Jackson serializes dates to longs.

But, Gson serializes Date

2条回答
  •  没有蜡笔的小新
    2021-02-19 05:50

    You can do both direction with one type adapter:

    public class DateLongFormatTypeAdapter extends TypeAdapter {
    
        @Override
        public void write(JsonWriter out, Date value) throws IOException {
            if(value != null) out.value(value.getTime());
            else out.nullValue();
        }
    
        @Override
        public Date read(JsonReader in) throws IOException {
            return new Date(in.nextLong());
        }
    
    }
    

    Gson builder:

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateLongFormatTypeAdapter())
            .create();
    

提交回复
热议问题