我有一个简单的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);
我需要result
映射以包含类型为"startDate"
的值的键 Timestamp
。(com.google.firebase.Timestamp)
然而,result
包含key "startDate"
,类型LinkedTreeMap
的value包含纳秒和秒。
我尝试创建自定义反序列化器:
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。
这是firebase.Timestamp
反序列化的方式。如果您需要反序列化实际时间,则可以采取解决方法。将您的startDate,endDate设置为transient
,这样它们就不会出现在json字符串中,然后为它们添加辅助字段和初始化程序:
public class EventPOJO {
public EventPOJO() {
}
public String id, title;
transient public Timestamp startDate, endDate;
public long startSeconds;
public int startNanoSeconds;
public long endSeconds;
public int endNanoSeconds;
public void initFields() {
startSeconds = startDate.getSeconds();
startNanoSeconds = startDate.getNanoSeconds();
endSeconds = endDate.getSeconds();
endNanoSeconds = endDate.getNanoSeconds();
}
}
然后在initFields()
之前调用toJson(eventPOJO)
:
eventPOJO.initFields();
String json = gson.toJson(eventPOJO);
您应该得到类似的东西
{id=123, startSeconds=47245722.0, startNanoSeconds=436.0, endSeconds=47245726.0, endNanoSeconds=452.0}