POJO使用自定义解串器与Gson映射

时间:2020-05-15 15:12:22

标签: java gson

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

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映射包含类型为startDate Timestamp。 (com.google.firebase.Timestamp)

相反,result包含 startDate,其类型为LinkedTreeMap包含纳秒和秒。

我尝试创建自定义反序列化器

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

反序列化甚至都没有被调用,而且我仍在获取没有Timestamp对象的Map。

1 个答案:

答案 0 :(得分: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();