首页 > 解决方案 > 如何将json firestore时间戳序列化为日期?

问题描述

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

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

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:应为字符串,但在路径 $.dateOfEvent 处为 BEGIN_OBJECT

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

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

感谢您的时间和帮助。

标签: androidserializationgoogle-cloud-firestoretimestampgson

解决方案


Gson期待一个日期字符串,2020-02-27T09:00:00但它实际上是一个对象。你可以像这样设置你的类并添加一个辅助方法来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
  }
}


推荐阅读