POJO 使用自定义反序列化器与 Gson 进行映射

POJO to Map with Gson with custom deserializer

我有一个简单的 POJO class 看起来像这样:

public class EventPOJO {

    public EventPOJO() {
    }

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

我有一个 EventPOJO 实例,需要将这个实例反序列化为一个 Map<String, Object> 对象。

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

我需要 result 映射来包含 key startDatevalue 类型 Timestamp。 (com.google.firebase.Timestamp)

但是 result 包含 key startDate 和类型 LinkedTreeMapvalue包含纳秒和秒。

我尝试创建一个自定义解串器:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer());
Gson gson = gsonBuilder.create();
String json = gson.toJson(eventPOJO);
Map<String,Object> result = gson.fromJson(json, Map.class);

TimestampDeserializer.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);
    }
}

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

如果您需要一个结果作为 Map,那么为什么不使用 gson 简单地创建一个 Map:

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;
    }
}

然后调用

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