2016 年 12 月 27 日更新
正如许多人所提到的,将@JsonIgnore 换成@Exclude。
我终于想出了一个灵活的解决方案来处理 Dates 和 ServerValue.TIMESTAMP。这是来自Ivan V、Ossama 和puf 的示例。
我想不出一种方法来处理long 和HashMap<String, String> 之间的转换,但是如果您将属性嵌套在更通用的HashMap<String, Object> 中,它可以作为单个长值进入数据库("date", "1443765561874") 或 ServerValue.TIMESTAMP 哈希映射 ("date", {".sv", "servertime"})。然后当你把它拉出来时,它总是一个带有(“日期”,“某个长数字”)的 HashMap。然后,您可以使用 @JsonIgnore @Exclude 注释在您的 POJO 类中创建一个辅助方法(这意味着 Firebase 将忽略它并且不将其视为用于从数据库序列化/从数据库序列化的方法)以轻松获取从返回的 HashMap 中提取长值以在您的应用中使用。
POJO 类的完整示例如下:
import com.google.firebase.database.Exclude;
import com.firebase.client.ServerValue;
import java.util.HashMap;
import java.util.Map;
public class ExampleObject {
private String name;
private String owner;
private HashMap<String, Object> dateCreated;
private HashMap<String, Object> dateLastChanged;
/**
* Required public constructor
*/
public ExampleObject() {
}
public ExampleObject(String name, String owner, HashMap<String,Object> dateCreated) {
this.name = name;
this.owner = owner;
this.dateCreated = dateCreated;
//Date last changed will always be set to ServerValue.TIMESTAMP
HashMap<String, Object> dateLastChangedObj = new HashMap<String, Object>();
dateLastChangedObj.put("date", ServerValue.TIMESTAMP);
this.dateLastChanged = dateLastChangedObj;
}
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public HashMap<String, Object> getDateLastChanged() {
return dateLastChanged;
}
public HashMap<String, Object> getDateCreated() {
//If there is a dateCreated object already, then return that
if (dateCreated != null) {
return dateCreated;
}
//Otherwise make a new object set to ServerValue.TIMESTAMP
HashMap<String, Object> dateCreatedObj = new HashMap<String, Object>();
dateCreatedObj.put("date", ServerValue.TIMESTAMP);
return dateCreatedObj;
}
// Use the method described in https://stackoverflow.com/questions/25500138/android-chat-crashes-on-datasnapshot-getvalue-for-timestamp/25512747#25512747
// to get the long values from the date object.
@Exclude
public long getDateLastChangedLong() {
return (long)dateLastChanged.get("date");
}
@Exclude
public long getDateCreatedLong() {
return (long)dateCreated.get("date");
}
}