How to serialize Date to long using gson?

I recently switched part of our serialization from Jackson to Gson . It turned out that Jackson serializes dates with long ones.

But, by default, Gson serializes dates in strings.

How do I serialize dates in longs when using Gson? Thanks.

+11
source share
2 answers

The adapter of the first type performs deserialization, and the second serializes.

 Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())) .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime())) .create(); 

Using:

 String jsonString = gson.toJson(objectWithDate1); ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class); assert objectWithDate1.equals(objectWithDate2); 
+19
source

You can do both directions with one type of adapter:

 public class DateLongFormatTypeAdapter extends TypeAdapter<Date> { @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(); 
+7
source

Source: https://habr.com/ru/post/1263665/


All Articles