如何将json firestore时间戳序列化为日期



我将日期存储在Firestore中。我从firestore得到了一个HashMap<String, Object>,我想从中重新创建我的对象。

在实施日期之前,工作代码为:

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

我现在添加了字段

@ServerTimestamp
private Date dateOfEvent;

但是当我尝试序列化它时,我得到了以下错误:

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为STRING,但在路径$.dateOfEvent 处为BEGIN_OBJECT

因为JsonElement"dateOfEvent"看起来像这样,因为它是Firestore时间戳:

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

谢谢你的时间和帮助。

Gson需要一个类似2020-02-27T09:00:00的Date字符串,但它实际上是一个对象。你可以这样设置你的类,并添加一个helper方法来获得dateOfEvent作为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
}
}

最新更新