I recently switched some of our serialization from Jackson
to Gson
. Found out that Jackson serializes dates to longs.
But, Gson serializes Dates to strings by default.
How do I serialize dates to longs when using Gson? Thanks.
Gson rawGson = new Gson(); SimpleDateFormat fmt = new SimpleDateFormat("MMM d, yyyy HH:mm:ss") private class DateDeserializer implements JsonDeserializer<Date> { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return new rawGson.
Serialization – Write JSON using Gson Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object.
The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. GSON also has two other parsers. The Gson JSON parser which can parse JSON into Java objects, and the JsonReader which can parse a JSON string or stream into tokens (a pull parser).
If you are not using spring boot and using normal spring application then you may create bean of GsonBuilder and support date-time format over there. It is supporting Java Standard format. 4. Gson Date to long
First, let's serialize an array of objects with Gson: 2. Serialize a Collection of Entities Next, let's do the same for a Collection of objects: 3. Change the Field Names of an Entity on Serialization Next, let's see how we can change the name of the field when we're serializing an entity.
Consider that you have to know which fields contain dates. You can specify you format Gson gson = builder.setDateFormat ("yyyy-MM-dd").create (); in this method instead of yyyy-MM-dd you can use anyother formats I'm on Gson 2.8.6 and discovered this bug today.
Custom GSON LocalDateSerializer Note that we are formatting default local date "2018-10-26" to "27-Oct-2018". 2. Custom GSON LocalDateTimeSerializer Note that we are formatting default local date "2018-10-26T11:09:05" to "27::Oct::2018 14::35::13".
First type adapter does the deserialization and the second one the serialization.
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();
Usage:
String jsonString = gson.toJson(objectWithDate1);
ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
assert objectWithDate1.equals(objectWithDate2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With