Gson Library Changing useful. Date

Asked

Viewed 680 times

2

When using the library GSON for the manipulation of JSON, I realized that by doing the parsers 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 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);

Exit 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.

Realize that the toString, apparently shows no change, already the date.getTimeis different.

first(before the JSON parse) 1508270523483

after (after parse JSON) 1508270523000

1 answer

1


When serializing to JSON, you end up losing the millisecond information. If you print the variable dataNoFormatoJson, you will see that she has a date in the format Oct 18, 2017 10:41:59 AM. By deserialize again to an object Date, this will come with the zeroed milliseconds.

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 you have 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.