0

我正在使用Android DDP 客户端库将我的 Android 客户端连接到Meteor-JS服务器。当我收到一个新对象时,我使用以下代码解析“createdAt”字段

private Map<String, Object> fields;
private Date timestamp;
/*...*/
timestamp = (Date) fields.get("createdAt");

我错误地认为它应该是Date类型。我得到一个错误消息的异常:

com.google.gson.internal.LinkedHashTreeMap cannot be cast to java.util.Date

如何正确解析 Meteor 发送的日期?

4

1 回答 1

0

Meteor-JS 向您发送一个 JSON。

// The Date value in the JSON response is a Unix timestamp.
// It gives the number of milliseconds since 1 January 1970 00:00:00 UTC.
// So we can do:
Double jsonDate = ((Map<String, Double>) fields.get("createdAt")).get("$date");
timestamp = new Date(jsonDate.longValue());

附言。我建议将时间戳存储为long字段而不是Date.

于 2015-03-29T02:29:49.500 回答