Gson Library Changing util.Date

1

When using the GSON library for JSON manipulation, I noticed that when parsers are done the date is being changed, it's tiny, but it's enough to break my unit test with JUnit . >

Follow a sketch code to show the strange behavior.

Gson gson = new Gson();

Date data = new Date();

String dataNoFormatoJSON = gson.toJson(data);
Date dataDoJSON = gson.fromJson(dataNoFormatoJSON, Date.class);

long dataTime = data.getTime();
long dataDoJSONTime = dataDoJSON.getTime();

System.out.println(data + " - " + dataTime);
System.out.println(dataDoJSON + " - " + dataDoJSONTime);

Output from this code:

Tue Oct 17 17:02:03 GFT 2017 - 1508270523483
Tue Oct 17 17:02:03 GFT 2017 - 1508270523000

First the toString() of Date and then the date.getTime() which is the representation of that date in long .

Notice that toString , apparently does not show any change, since date.getTime is different.

first (before parse JSON) 1508270523483

After (after parse JSON) 1508270523000

    
asked by anonymous 17.10.2017 / 22:12

1 answer

0

When serializing to JSON, you end up losing information on milliseconds. If you start the dataNoFormatoJson variable, you'll see that it has a date in Oct 18, 2017 10:41:59 AM format. When deserializing back to a Date object, it will come with the milliseconds zeroed.

An alternative is to use a date format that has milliseconds:

Gson gson = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    .create();

Another alternative is to create a JsonSerializer and a JsonDeserializer and serialize the representation in long of the date that has the milliseconds (or other representation you want).

JsonSerializer<Date> dateSerializer = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
    if(src == null) {
      return null;
    }

    return new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> dateDeserializer = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if(json == null) {
      return null;
    }

    return new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
    .registerTypeAdapter(Date.class, dateSerializer)
    .registerTypeAdapter(Date.class, dateDeserializer)
    .create();
    
18.10.2017 / 14:51