Java POJO要与带有自定义反序列化器的Gson映射

Java POJO要与带有自定义反序列化器的Gson映射,java,gson,Java,Gson,我有一个简单的POJO类,如下所示: public class EventPOJO { public EventPOJO() { } public String id, title; // Looking for an annotation here public Timestamp startDate, endDate; } 我有一个EventPOJO实例,需要将该实例反序列化为Map对象 Gson gson = new GsonBuilder()

我有一个简单的POJO类,如下所示:

public class EventPOJO {

    public EventPOJO() {
    }

    public String id, title;
    // Looking for an annotation here
    public Timestamp startDate, endDate;
}
我有一个EventPOJO实例,需要将该实例反序列化为
Map
对象

Gson gson = new GsonBuilder().create();
String json = gson.toJson(eventPOJO);
Map<String,Object> result = new Gson().fromJson(json, Map.class);
timestadeserializer.java

public class TimestampDeserializer implements JsonDeserializer<Timestamp> {
    @Override
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        //not sure how to retrieve the seconds from the parameters
        return new Timestamp(999999999, 0);
    }
}
公共类时间反序列化器实现JsonDeserializer{
@凌驾
公共时间戳反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext)引发JsonParseException{
//不确定如何从参数中检索秒数
返回新的时间戳(99999999,0);
}
}

反序列化甚至从未被调用过,我仍然得到一个没有时间戳对象的映射。

如果您需要一个结果作为映射,那么为什么不直接创建一个映射而不使用gson:

public class EventPOJO {

    public EventPOJO() {
    }

    public EventPOJO(String id) {
        this.id = id;
    }

    public String id, title;
    // Looking for an annotation here
    public Timestamp startDate, endDate;

    public Map<String, Object> getMap() {
        Map<String, Object> res = new HashMap<>();
        res.put("id", id);
        res.put("title", title);
        res.put("startDate", startDate);
        res.put("endDate", endDate);
        return res;
    }
}
公共类EventPOJO{
公共事件pojo(){
}
公共事件POJO(字符串id){
this.id=id;
}
公共字符串id、标题;
//在这里寻找注释吗
公共时间戳startDate、endDate;
公共地图getMap(){
Map res=新的HashMap();
放置(“id”,id);
决议草案(“标题”,标题);
res.put(“开始日期”,开始日期);
存托凭证(“结束日期”,结束日期);
返回res;
}
}
然后打电话

Map<String, Object> result = eventPOJO.getMap();
Map result=eventPOJO.getMap();

请说明如何设置时间戳类型的字段:startDate、endDate。例如,我用手动创建的时间戳初始化了POJO,结果显示很好:{id=123,startDate=Jan 13,3920 8:07:07 AM}@HoRn我的EventPOJO对象是从数据库响应(DocumentSnapshot)创建的:
EventPOJO EventPOJO=DocumentSnapshot.toObject(EventPOJO.class)我在调试模式下检查:这些字段已设置,并且是实际的时间戳对象(com.google.firebase.Timestamp)
Map<String, Object> result = eventPOJO.getMap();