How to serialize a json firestore Timestamp to Date?

Viewed 1900

I store a Date in Firestore. I get an HashMap<String, Object> from firestore and i want to recreate my object from it.

Before implementing the Date the working code was :

HashMap<String, Object> document = new HashMap<String, Object>();
document.put("name", "name");
JSONElement jsonElement = gson.toJsonTree(document);
Event event = gson.fromJson(jsonElement , Event.class);

I have now add the field

@ServerTimestamp
private Date dateOfEvent;

But when i try to serialize it i get the following error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT at path $.dateOfEvent

Because the JsonElement "dateOfEvent" look like this because it's a Firestore Timestamp:

{"dateOfEvent": {"nanoseconds":0,"seconds":1584921600}, "name": "test Event"}

Thanks for your time and your help.

1 Answers

Gson is expecting a Date string like 2020-02-27T09:00:00 but it's actually an object. You could setup your classes like this and add a helper method to get dateOfEvent as a Date:

class Event {
  private String name;
  private MyDate date;
}

class MyDate {
  private Long nanoseconds;
  private Long seconds;

  // getters/setters for nanoseconds, seconds...

  public Date asDate() {
    // convert to date
  }
}

Related