android - 如何将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"}
感谢您的时间和帮助。
解决方案
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
}
}
推荐阅读
- python - Django:找不到这样的文件或目录
- windows - Windows Batch - 查找一行并替换为文本
- python - Django 2.2:如何在 Django Admin 中修改特定页面?
- java - 使用 printf 打印列
- jenkins - Jenkins Job 在 24 小时内检查失败的工作
- python - 如何减少循环
- ruby-on-rails - 将环境变量分离到不同的环境中
- angular - Maximum call stack size exceeded (Angular8)
- django - Django:为当前用户过滤数据库
- flutter - Firestore 不存储来自 TextField 的新行