我有一个简单的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。
答案 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();